As I want to control the output from all endpoints of my application including for endpoints not explicitly defined, I created a simple DefaultController looking like this.
#RestController
public class DefaultController {
#RequestMapping("/**")
public void unmappedRequest(HttpServletRequest request) {
throw new ResourceNotFoundException();
}
}
I also have a #ControllerAdvice error controller that extends ResponseEntityExceptionHandler and overrides all methods from that class, and specifically
#Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if(HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute("javax.servlet.error.exception", ex, 0);
}
SearchOutput output = new SearchOutput(body);
return new ResponseEntity<>(output, headers, status);
}
I also added a method to handle the ResourceNotFoundException thrown by the default mapper.
#ExceptionHandler(ResourceNotFoundException.class)
public #ResponseBody ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
HttpStatus status = HttpStatus.NOT_FOUND;
ErrorOutput out = new ErrorOutput("Resource not found", status);
return this.handleExceptionInternal(ex, out, headers, status, request);
}
I declared error.whitelabel.enabled:false and added exclude={ErrorMvcAutoConfiguration.class} to the #EnableAutoConfiguration annotation, and still have two problems when running this application in a standalone Tomcat container:
ErrorPageFilter complains about the fact that it Cannot forward to error page for request [/something/not/existing] as the response has already been committed every time the ResourceNotFoundException is thrown;
when the browser (automatically) requests favicon.ico, a Failed to invoke #ExceptionHandler method error for the handleExceptionInternal method is logged, with description Could not find acceptable representation.
Also - is this an acceptable way to deal with non-existing resources?
Related
I have a Spring Boot server that listens on endpoint. I accept #RequestBody as an object:
class Body {
private String name;
}
I want it to accept requests like:
{
"name": "some_name"
}
However, it also accepts:
{
"name": "some_name",
"dummy key":"dummy key value"
}
In that case I want it to throw error. How can I achieve it?
You can do this in the controller when saving:
#PostMapping("/add")
public ResponseEntity<Body> registerUser(#Valid #RequestBody Body saveUser) {
Body createdUser = userService.save(saveUser);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}
When Spring finds an argument annotated with #Valid, it automatically validates the argument and throws an exception if the validation fails.
or you can do this as well:
In the application.properties
spring.jackson.deserialization.fail-on-unknown-properties=true
This helps us to make deserialization fail on unknown properties and throw an exception which we can handle using handleHttpMessageNotReadable
Create controller advice to handle exceptions
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
return new ResponseEntity("Your Response Object",
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I'd like to do custom exception handling for a REST API.
This is the code I have.
Controller Endpoint
#PatchMapping(value="/customer/name", produces = "application/json")
public ResponseEntity<Customer> updateName(
#RequestParam(value="customerId") Long customerId,
#RequestParam(value="name") String name){
customerRepository.updateCustomerName(customerId, name);
Customer updatedCustomer = customerRepository.findCustomer(customerId);
return new ResponseEntity<Customer>(updatedCustomer, HttpStatus.OK);
}
Custom Exception Handling Class
#ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler{
#ExceptionHandler(value = {Exception.class})
public ResponseEntity<Object> handleAll(Exception ex, WebRequest request) {
return new ResponseEntity<>(
ex, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
If I force an error inside the endpoint method (such as adding the null pointer exception below), it will correctly enter the handleAll method and return the custom error.
String x = null;
int y = x.length();
But, if instead of that, I generate the error by going to Postman and pass a String instead of a Long in the customerId parameter, it doesn't enter the custom error class.
In fact, it never enters the controller method.
How to make the custom error class catch and display custom error for that as well?
thanks
try to override handleMethodArgumentTypeMismatch
#ExceptionHandler({MethodArgumentTypeMismatchException.class})
public ResponseEntity<Object> handleMethodArgumentTypeMismatch( MethodArgumentTypeMismatchException ex, WebRequest request) {
return ResponseEntity
}
I am using java and Spring Boot to create a basic REST API.
How would I check if a request is any of this {GET, POST, PUT, DELETE}?
This is the method in the exception handler.
#Order(Ordered.HIGHEST_PRECEDENCE)
#Component
#ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {
#Override
protectedResponseEntity<Object>handleHttpMessageNotReadable(
HttpMessageNotReadableException ex,HttpHeaders headers, HttpStatus
status, WebRequest request) {
String error = "Not a JSON object";
ExceptionResponse response = ExceptionResponse.getBuilder()
.addVerb("POST")
.addURL(Global.URL)
.addMessage(error).build();
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
}
Just cast your WebRequest into HttpServletRequest and find the method.
((HttpServletRequest) request).getMethod();
Edit :
As per the comment OP's handler is not invoked.
Below is an example of Exception Handler with Order precedence.
#Order(Ordered.HIGHEST_PRECEDENCE)
#ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
((HttpServletRequest) request).getMethod();
// Do Something
}
}
I fixed it by using this
((ServletWebRequest) request).getMethod();
My controller has the following method:
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public void save(#RequestBody #Valid final User resource) {
createInternal(resource);
}
Because of the #Valid before the resource parameter, I expect it to be intercepted by the following exception handler when I pass in a NULL into a nullable=false on my #Column of my entity,
#Override
protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException e,
final HttpHeaders headers,
final HttpStatus status,
final WebRequest request) {
log.info("Bad Request: {}", ex.getMessage());
log.debug("Bad Request: ", ex);
...
return handleExceptionInternal(e, dto, headers, HttpStatus.BAD_REQUEST, request);
}
But it seems I can only handle it this way instead:
#ExceptionHandler(value = { ConstraintViolationException.class,
DataIntegrityViolationException.class })
public final ResponseEntity<Object> handleBadRequest(final RuntimeException e,
final WebRequest request) {
...
return handleExceptionInternal(ex, apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
Why isn't the handleMethodArgumentNotValid exception handler picking it up like it should?
Before your 'handleMethodArgumentNotValid' has a chance to fire, DefaultHandlerExceptionResolver handles this
or if you want to handle declare , #ExceptionHandler(MethodArgumentNotValidException.class)
An #RequestBody method parameter can be annotated with #Valid, in
which case it will be validated using the configured Validator
instance. When using the MVC namespace or the MVC Java config, a
JSR-303 validator is configured automatically assuming a JSR-303
implementation is available on the classpath.
Just like with #ModelAttribute parameters, an Errors argument can be
used to examine the errors. If such an argument is not declared, a
MethodArgumentNotValidException will be raised. The exception is
handled in the DefaultHandlerExceptionResolver, which sends a 400
error back to the client. Before your 'handleMethodArgumentNotValid'
has a chance to fire, this is handndf
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody
Why isn't the handleMethodArgumentNotValid exception handler picking
it up like it should?
Spring container (during start up) scans through all of the controller(s) methods annotated with #RequestMapping and #ExceptionHandler.
Later, when the request comes with an url, the controller method will be identified using handlermapping, then injects all the required dependencies (controller method arguments) like Model, HttpRequest, etc.. and delegates the call the controller method to serve the input request.
Since your handleMethodArgumentNotValid is not annotated with either #RequestMapping or #ExceptionHandler, Spring container can't recognise this method.
#ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<> handleConstraintViolation(ConstraintViolationException ex,
WebRequest request) {
// error handeling
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
More details at https://www.baeldung.com/global-error-handler-in-a-spring-rest-api
I have created a Spring MVC REST service using Bean Validation 1.2 with the following method:
#RequestMapping(value = "/valid")
public String validatedMethod(#Valid ValidObject object) {
}
If object isn't valid, Tomcat informs me that The request sent by the client was syntactically incorrect. and my validatedMethod is never called.
How can I get the message that was defined in the ValidObject bean? Should I use some filter or interceptor?
I know that I can rewrite like below, to get the set of ConstraintViolations from the injected Validator, but the above seems more neat...
#RequestMapping(value = "/valid")
public String validatedMethod(ValidObject object) {
Set<ConstraintViolation<ValidObject>> constraintViolations = validator
.validate(object);
if (constraintViolations.isEmpty()) {
return "valid";
} else {
final StringBuilder message = new StringBuilder();
constraintViolations.forEach((action) -> {
message.append(action.getPropertyPath());
message.append(": ");
message.append(action.getMessage());
});
return message.toString();
}
}
I believe a better way of doing this is using ExceptionHandler.
In your Controller you can write ExceptionHandler to handle different exceptions. Below is the code for the same:
#ExceptionHandler(MethodArgumentNotValidException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ResponseBody
public ValidationFailureResponse validationError(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
final List<FieldError> fieldErrors = result.getFieldErrors();
return new ValidationFailureResponse((FieldError[])(fieldErrors.toArray(new FieldError[fieldErrors.size()])));
}
When you send a bad request to the Controller, the validator throws an exception of type MethodArgumentNotValidException. So the ideal way would be to write an exception handler to specifically handle this exception.
There you can create a beautiful response to tell the user of things which went wrong.
I advocate this, because you have to write this just once and many Controller methods can use it. :)
UPDATE
When you use the #Valid annotation for a method argument in the Controller, the validator is invoked automatically and it tries to validate the object, if the object is invalid, it throws MethodArgumentNotValidException.
If Spring finds an ExceptionHandler method for this exception it will execute the code inside this method.
You just need to make sure that the method above is present in your Controller.
Now there is another case when you have multiple Controllers where you want to validate the method arguments. In this case I suggest you to create a ExceptionResolver class and put this method there. Make your Controllers extend this class and your job is done.
Try this
#RequestMapping(value = "/valid")
public String validatedMethod(#Valid ValidObject object, BindingResult result) {
StringBuilder builder = new StringBuilder();
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
builder.append(error.getField() + " : " + error.getDefaultMessage());
}
return builder.toString();
}
When you use #Valid and doing bad request body Spring handle MethodArgumentNotValidException
You must create special class and extend ResponseEntityExceptionHandler and override handleMethodArgumentNotValid
Example
#ControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(UserExistException.class)
public ResponseEntity<Object> handleUserExistException(
UserExistException e, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.BAD_REQUEST.value());
body.put("error", HttpStatus.BAD_REQUEST.getReasonPhrase());
body.put("message", e.getMessage());
body.put("path", request.getDescription(false).replace("uri=", ""));
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.BAD_REQUEST.value());
body.put("error", HttpStatus.BAD_REQUEST.getReasonPhrase());
body.put("path", request.getDescription(false).replace("uri=", ""));
return new ResponseEntity<>(body, headers, status);
}
}
The answer by #dharam works.
For users at Spring v4.3, Here's a nice implementation which uses a Custom Exception class to handle exception by type.
#RestControllerAdvice
public class CustomExceptionClass extends ResponseEntityExceptionHandler{
#ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleException(MethodArgumentNotValidException ex, WebRequest req){
// Build your custom response object and access the exception message using ex.getMessage()
}
}
This method will enable handling all #Valid exceptions across all of your #Controller methods in a consolidated way