can some one explain me what is the usage of extending ResponseEntityExceptionHandler. If Ido not extend also ResponseEntityExceptionHandler GlobalExceptionHandler is working and sending the response to client.
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler{
@ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof UserNotFoundException) {
HttpStatus status = HttpStatus.NOT_FOUND;
UserNotFoundException unfe = (UserNotFoundException) ex;
return handleUserNotFoundException(unfe, headers, status, request);
} else if (ex instanceof ContentNotAllowedException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
ContentNotAllowedException cnae = (ContentNotAllowedException) ex;
return handleContentNotAllowedException(cnae, headers, status, request);
} else {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleExceptionInternal(ex, null, headers, status, request);
}
}
}
@ControllerAdvice
public class GlobalExceptionHandler{
@ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
if (ex instanceof UserNotFoundException) {
HttpStatus status = HttpStatus.NOT_FOUND;
UserNotFoundException unfe = (UserNotFoundException) ex;
return handleUserNotFoundException(unfe, headers, status, request);
} else if (ex instanceof ContentNotAllowedException) {
HttpStatus status = HttpStatus.BAD_REQUEST;
ContentNotAllowedException cnae = (ContentNotAllowedException) ex;
return handleContentNotAllowedException(cnae, headers, status, request);
} else {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return handleExceptionInternal(ex, null, headers, status, request);
}
}
}
CodePudding user response:
ResponseEntityExceptionHandler is used when one is generally satisfied with Spring's default ExceptionHandlers - except for a few, which may then be overridden.
Have a look at all the protected methods in the API documentation: ResponseEntityExceptionHandler
Your GlobalExceptionHandler is already accepting any Exceptions and custom handling two specific Exceptions.
If you insist on using ResponseEntityExceptionHandler, a similar effect may be achieved by extending the class and implementing handleExceptionInternal():
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
public handleExceptionInternal() {
...
}
}