Skip to content

Latest commit

 

History

History

day-07

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Day 07

  • n-Tier Architecture
  • SOLID
  • Service Layer Implementation
  • Abstaction
  • ApiResponse Design
  • ApiErrorResponse Design
  • Controller-based Error Handling
    • @ExceptionHandler
  • Global Error Handling
    • @ControllerAdvice

Global Error Handlig

@ControllerAdvice mekanizması ile global olarak hataları yönetmek mümkündür. @ExceptionHandler bu mekanizma ile tip güvenliğini sağlayarak farklı hatalara karşı farklı aksiyonların alınabilmesine olanak sağlamaktadır.

Global Error Handling

  • Rest isteklerine cevap olarak üretilen StatusCode ifadeleri tam olarak açıklayıcı olmayabilir.
  • Böylesi durumlarda mutlaka bir body ifadesiyle dönüş hakkında/hata hakkında detaylı bilgiler sunulmalıdır.

NotFoundExcepiton

Endpoint bulunamaması durumunda tüm NotFoundException ifadeleri için yazılmış bir hata yönetim metodur.

// Not Found Hataları için
@ExceptionHandler(NotFoundException.class)
    public ResponseEntity<?> handleNotFoundExceptions(NotFoundException ex,
            WebRequest request) {

        var response = new ApiErrorResponse<>();
        response.setHttpStatus(HttpStatus.NOT_FOUND);
        response.setStatusCode(HttpStatus.NOT_FOUND.value());

        // response.setTimestamp(ResponseMessage.timestamp);
        response.setPath(request.getDescription(false));
        response.setErrors(Arrays.asList(ex.getMessage()));

        log.error(response.toString());
        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(response);
    }

TypeMismatchException

Parametre olarak beklenen tip gelen, giriş olarak uygulanan tip bilgilerinin uyuşmaması durumunda ortaya çıkan hatadır. İllgili hatanın yönetimi aşağıdaki gibi yapılır.

@Override
    protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers,
            HttpStatus status, WebRequest request) {
        // return super.handleTypeMismatch(ex, headers, status, request);

        var response = new ApiErrorResponse<>();
        response.setPath(request.getDescription(false));
        response.setErrors(Arrays.asList(ex.getMessage(), "Required Type: " + ex.getRequiredType()));

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(response);
    }

application.properties

ERROR HANDLING (ErrorProperties)

server.error.path=/error # the error path server.error.include-stacktrace=never server.error.whitelabel.enabled=true

Kaynaklar

  1. Handling Standard Spring MVC Exceptions
  2. Error Handling for REST with Spring
  3. Custom Error Message Handling for REST API
  4. Guide to Spring Boot REST API Error Handling
  5. Bootstrap a Simple Application
  6. LIKE Queries in Spring JPA
  7. Common Application Properties

Postman

Postman API Test

API-Docs