- n-Tier Architecture
- SOLID
- Service Layer Implementation
- Abstaction
- ApiResponse Design
- ApiErrorResponse Design
- Controller-based Error Handling
- @ExceptionHandler
- Global Error Handling
- @ControllerAdvice
@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.
- 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.
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);
}
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);
}
server.error.path=/error # the error path server.error.include-stacktrace=never server.error.whitelabel.enabled=true