what is the usage of extending ResponseEntityExceptionHandler? - spring

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);
}
}
}

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() {
...
}
}

Related

#ControllerAdvice not throwing exception

I am handling exceptions globally in CustomHandler class. I could see while debugging this class is catching exceptions, but not throwing them to client. Please let me know what i am missing...
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Server Error", details);
return new ResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
#ExceptionHandler(ConstraintViolationException.class)
public final ResponseEntity<Object> constraintValidationException(
ConstraintViolationException e) {
List<String> details = new ArrayList<>();
for (ConstraintViolation violation : e.getConstraintViolations()) {
details.add(violation.getMessage());
}
ErrorResponse error = new ErrorResponse("Validation Failed", details);
return new ResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
}
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> details = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
}
ErrorResponse error = new ErrorResponse("Validation Failed", details);
return new ResponseEntity(error, HttpStatus.UNPROCESSABLE_ENTITY);
}
Create your own application specific exceptions and handle them. E.g: public class MyAppEx extends RuntimeException {}. Catch the Exception.class and then throw your exception:
try {
// something goes wrong
} catch (Exception e) {
throw new MyAppEx("details of the exception");
}
Replace:
#ExceptionHandler(MyAppEx.class)
public final ResponseEntity<Object> handleAllExceptions(MyAppEx ex, WebRequest request) {..}

Required parameters exception doesn't work in spring boot 2.x

In my spring boot application, I tried to handled the Required parameter exception. This question may be duplicated. But the answers posted don't help me.
My controller
#GetMapping("/test")
public ObjectId test(#RequestBody OIdLGroupIds OIdLGroupIds,#RequestParam ObjectId _id){
return videoService.test();
}
My global exception handler is like following.
#RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Server Error", details);
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
#ExceptionHandler(NotFoundHandler.class)
public final ResponseEntity<Object> handleRecordNotFoundException(NotFoundHandler ex, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", "Record not found");
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Record Not Found", details);
return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDate.now());
body.put("status", status.value());
Set<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toSet());
body.put("details", errors);
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
It doesn't throw any details (Body is blank). But the response status is 400 Bad Request. But when I comment all above codes, it throws default exceptions with body.
I tried this also
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String name = ex.getParameterName();
System.out.println(name);
logger.error(name + " parameter is missing");
return super.handleMissingServletRequestParameter(ex, headers, status, request);
}
I have tried in many ways, But no luck. Did I miss anything? Please help me. Thanks in advance.
Empty request body raises HttpMessageNotReadableException.
#RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
String name = ex.getParameterName();
System.out.println(name);
logger.error(name + " parameter is missing");
return super.handleMissingServletRequestParameter(ex, headers, status, request);
}
#Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
System.out.println(ex.getMessage());
logger.error("Request body is missing");
return super.handleHttpMessageNotReadable(ex, headers, status, request);
}
}
If you allow empty body, use #RequestBody(required = false).

Spring missing query parameters exception handling

I have this code:
#GetMapping(value = "/users/{id}")
#ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( #PathParam("id") #PathVariable("id") #RequestParam Long id) {
return adminService.getUserById(id);
}
and this code:
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#Override
public ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return error_with_my_info;
}
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {{
return error_with_my_info;
}
...
}
The problem is that when I send a request WITHOUT a parameter, it is handleHttpMessageNotReadable that is called, not handleMissingServletRequestParameter.
Why is that?
Can other API endpoints affect this behaviour, like having a PUT request handler with the same endpoint?
How can I make it so that handleMissingServletRequestParameter?
Improvised :
#GetMapping(value = "/users")
#ResponseStatus(HttpStatus.OK)
public DtoUser getUserById( #RequestParam(value="id" , required=true)Long id) {
return adminService.getUserById(id);
}
localhost:8080?id=test
now if you dont pass id it will give you handleMissingServletRequestParameter.

Spring validation returns long error messages, not just the customized message

Spring validation returns long error message instead of the customized once.
This is the section of code in the dto.
public class RequestDto implements Serializable {
#NotNull(message="{id.required}")
private Long id;
}
In controller added the #Valid for input.
#RequestMapping(value = ApiPath.PATH, method = RequestMethod.POST, produces = { "application/xml",
"application/json" })
public #ResponseBody ResultDecorator saveRequest(
#Valid #RequestBody RequestDto msaDisabScreenRequestDto) throws Exception {
}
API returns the following error.
<message>Validation failed for argument at index 0 in method: public om.gov.moh.msa.framework.resolver.ResultDecorator om.controller.MaController.saveRequest(om..dto.RequestDto) throws java.lang.Exception, with 1 error(s): [Field error in object 'requestDto' on field 'id': rejected value [null]; codes [NotNull.requestDto.id,NotNull.id,NotNull.java.lang.Long,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [requestDto.id,id]; arguments []; default message [civilId]]; **default message [ID is required.]]** </message>
Here the custom message is present at the end. (default message [ID is required.)
Using Controller advice for global exception and I'm overriding handleMethodArgumentNotValid. How can I return only the custom message here?
#Order(Ordered.HIGHEST_PRECEDENCE)
#ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
/**
* Spring validation related exception
*/
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
}
You can get default/custom message like result.getFieldError("yourFieldName").getDefaultMessage()
You can catch error messages either through controller method which should look like this
#RequestMapping(value = ApiPath.PATH, method = RequestMethod.POST, produces = { "application/xml", "application/json" })
public #ResponseBody ResultDecorator saveRequest(#Valid #RequestBody RequestDto msaDisabScreenRequestDto, BindingResult result) throws Exception {
if(result.hasErrors()){
String errorMessage = result.getFieldError("yourFieldName").getDefaultMessage();
}
}
Or through Global Exception handler
Updated
#Order(Ordered.HIGHEST_PRECEDENCE)
#ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
/**
* Spring validation related exception
*/
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
//New Code
BindingResult bindingResult = ex.getBindingResult();
String errorMessage = result.getFieldError("yourFieldName").getDefaultMessage();
//---------------
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
apiError.setMessage(errorMessage);
return buildResponseEntity(apiError);
}
}
Thanks Afridi,
Created a string buffer and added all the error messages into that.
/**
* Spring validation related exception
*/
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
final StringBuffer errors = new StringBuffer();
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.append("\n");
errors.append(error.getField() + ": " + error.getDefaultMessage());
}
apiError.setMessage(errors.toString());
return buildResponseEntity(apiError);
}
As Afridi said in #ControllerAdvice can do this also:
#ExceptionHandler(value = MethodArgumentNotValidException.class)
#SuppressWarnings("unchecked")
#ResponseBody
public Result methodArgumentNotValidExceptionHandler(HttpServletRequest req, HttpServletResponse response, MethodArgumentNotValidException e) throws IOException {
String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
// todo return to your custom result
}
There are two point :
Exception class is MethodArgumentNotValidException
The first Error getDefaultMessage() can get your custom message in Annotation
In WebFlux :
Handle WebExchangeBindException for customising the default error message of #Valid
#ControllerAdvice
public class ValidationHandler {
#ExceptionHandler(WebExchangeBindException.class)
public ResponseEntity<List<String>> handleException(WebExchangeBindException e) {
var errors = e.getBindingResult()
.getAllErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(errors);
}
}
Reference : https://www.vinsguru.com/spring-webflux-validation/

Spring Boot: How to handle 400 error caused by #RequestParam?

public String(#RequestParam Integer id) {
// ...
}
If id parameter cannot be found in the current request, I will get 400 status code with empty response body. Now I want to return JSON string for this error, how can I make it?
PS: I don't want to use #RequestParam(required = false)
try to use #PathVariable, hope it will meets your requirement.
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
I've made it.
Just override handleMissingServletRequestParameter() method in your own ResponseEntityExceptionHandler class.
#Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
log.warn("miss Request Param");
return new ResponseEntity<>(new FoxResponse(ErrorCode.ARG_INVALID), status);
}
Just had the same problem, but exception thrown is MethodArgumentTypeMismatchException. With #ControllerAdvice error handler all data about #RequestParam error can be retrieved. Here is complete class that worked for me
#ControllerAdvice
#RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class ControllerExceptionHandler {
#ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
#ResponseBody
public Map<String, String> handleServiceCallException(MethodArgumentTypeMismatchException e) {
Map<String, String> errMessages = new HashMap<>();
errMessages.put("error", "MethodArgumentTypeMismatchException");
errMessages.put("message", e.getMessage());
errMessages.put("parameter", e.getName());
errMessages.put("errorCode", e.getErrorCode());
return errMessages;
}
}

Resources