Sample Project Attached Here
I am following this article API Error Handling (also please suggest if there is a better way to do this) to handle exceptions and validations in a generic way in my spring boot rest service. (i am new to spring and rest, so i am going through different articles for my requirement)
Basic idea about the requirement:
(Need to validate the POST request and send the validation errors to the client in a structure way. There could be multiple validation errors)
Whenever i get a POST request from my client, i need to validate the RequestBody. So I added #Valid on the parameter and #NotNull on the properties which i want to validate. Upon receiving the POST request spring is validating the request and throwing MethodArgumentNotValidException which is fine since i have some mandatory field missing.
I am handling it in a common place with #ControllerAdvice. After hitting the appropriate method handleMethodArgumentNotValid(...), i am constructing my custom error response APICustomError which i following from the above mentioned article.
When i have multiple validation errors, i am able to loop all the errors and adding it to a list and constructing the ResponseEntity with my custom error.
But the returned ResponseEntity does not have my added validation errors.
i understood the article and implemented the same in my project but really didn't get what i am missing.
The below is the output said in the article and what i am expecting is:
{
"apierror":{
"status":"BAD_REQUEST",
"timestamp":"10-07-2019 12:53:24",
"message":"Validation error",
"subErrors":[
{
"object":"person",
"field":"id",
"rejectedValue":null,
"message":"ID cannot be null"
},
{
"object":"person",
"field":"name",
"rejectedValue":null,
"message":"name cannot be null"
}
]
}
}
but below is what i am getting. i don't see the subErrors part at all.
{"message":"Validation Error","debugMessage":null,"detail":null,"httpStatus":"BAD_REQUEST","timestamp":"2019-07-10T17:08:00.52"}
Any help is appreciated.
You need to add getter and setters in APICustomError for properly serialize your object. Also you need public constructor and getter/setters for inner class APIValidationError. I suggest you use Lombok.
After that you will see the errors, something like this...
{
"message": "Validation Error",
"debugMessage": null,
"subErrors": [
{
"object": "personDTO",
"field": "id",
"rejectedValue": null,
"validationErrorMessage": "ID cannot be null."
}
],
"detail": null,
"httpStatus": "BAD_REQUEST",
"timestamp": "2019-07-10T10:25:44.1705441"
}
Try this one
In your controller advice
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Response response = new Response();
List<FieldError> errors = ex.getBindingResult().getFieldErrors();
List<SubError> errors = new ArrayList<>();
for (FieldError e : errors) {
SubError error = new SubError():
error.setMessage(String.format(MESSAGE_FORMAT, egetCOde));
errors.add(error);
}
response.setSubError(errors);
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
Related
In my Spring Boot application, I specified my API using OpenApi 3.0.0. When I test its response to bad input, I'm not happy with some of the error messages. The messages are useful when Hibernate can't handle my input. They include the class, field, and even the illegal value. But when Spring Boot rejects my input without even entering my code, I just get the vague message The request cannot be fulfilled due to bad syntax. There's no information about what field is bad, or what object holds the bad field value.
When I specify my DTO in the .yaml file, two fields are required:
MenuItemOptionDto:
type: object
description: Option for a MenuItem
properties:
name:
type: string
deltaPrice:
type: number
description: Floating point price. Strings are easier to work with.
id:
type: integer
format: int32
required:
- name
- deltaPrice
But suppose I submit a DTO with a missing deltaPrice, like this: {"name": "onions"} The error message just says The request cannot be fulfilled due to bad syntax. I want the error message to say which DTO is incorrect, and which field is missing.
I have specified three relevant application properties. Any one of these will give me Hibernate validation error messages, but none give me spring-boot validation messages:
server.error.include-message=always
server.error.include-binding-errors=always
server.error.include-exception=true
And I've received advise to add a validator bean to my main application, which didn't help:
#ComponentScan(basePackages = {"com.myWork.dummy","org.openapitools",})
#EnableCaching
#SpringBootApplication
public class ServerMaster implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(ServerMaster.class);
public static void main(String[] args) {
new SpringApplication(ServerMaster.class).run(args);
}
#Override
public void run(String... arg0) { ... }
// This was suggested at https://stackoverflow.com/questions/49538896/spring-boot-error-message-doesnt-work
// in order to give me better error messages when OpenAPI validations are triggered, but it doesn't help.
#Bean public Validator validator() {
return new LocalValidatorFactoryBean();
}
}
When I generate the code, it doesn't matter if I turn on the performBeanValidation or useBeanValidation options. The generated code doesn't change. Either way, the #NotNull annotations are applied to the getters for the name and deltaPrice fields, and these are getting honored by the server, but without useful error messages.
Finally, I'm using Spring-Boot 2.3.4, and I declare a dependency on Spring Boot annotations:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Spring-Boot correctly rejects the input because the OpenAPI generator puts #NotNull annotations on the getters of the generated MenuItemOptionDTO, but since the code is generated, I can't customize them with an error message, and I don't want to turn off the generator. How can I get Spring or OpenAPI to give me better error messages?
Test Case
To see these messages in action, check out the code at https://github.com/SwingGuy1024/SpringBootDemo.22.05.25
The default SpringBoot error-handler does not provide a response body for MethodArgumentNotValidException:
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return this.handleExceptionInternal(ex, (Object)null, headers, status, request);
}
The good news: you can override this in your GlobalResponseExceptionHandler class:
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
return handleExceptionInternal(ex, ex.getBindingResult(), headers, status, request);
}
In the above code, we simply return the entire binding-result as the response body. If you want to, you can tweak this (e.g. only include the errors).
When you call the controller with the invalid payload, you'll now get the following response:
{
"timestamp": "2022-05-28T19:40:47.295+00:00",
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"message": "Validation failed for object='menuItemOptionDto'. Error count: 1",
"errors": [
{
"codes": [
"NotNull.menuItemOptionDto.deltaPrice",
"NotNull.deltaPrice",
"NotNull.java.math.BigDecimal",
"NotNull"
],
"arguments": [
{
"codes": [
"menuItemOptionDto.deltaPrice",
"deltaPrice"
],
"arguments": null,
"defaultMessage": "deltaPrice",
"code": "deltaPrice"
}
],
"defaultMessage": "must not be null",
"objectName": "menuItemOptionDto",
"field": "deltaPrice",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"path": "/demo/admin/menuItem/addOption/1"
}
Based on OpenAPI generator to spring-boot with custom java validations
You can add some another validation layer in your code, which is independent of OpenAPI generator. This layer will be called from
PetsController and PetsController will validate only basic OpenAPI
known constraints.
You can add you validations not via annotations, but via xml config as shown here.
maybe something else.
Hack it a bit. I was looking for a solution in which my custom validation will be defined in OpenAPI spec same way as “required”.
Naturally I decided not to use solutions 1 or 2 (even thought it
might be the right way for a lot of cases). I found out the
openapi-generator actually provides a way of modifying the way the
code is generated. That means that I can actually define custom
constraint in OpenAPI specs as my own made up properties.
Please follow instructions in the above link for implementing last method.
I am working on an API and need to throw and exception that looks like this
"error": "sortBy parameter is invalid"
}
if the sort by parameter is not one of my predetermined values,
i have a few parameters to do this for
here is what my controller looks like
#GetMapping("/api/posts")
public ResponseEntity<List<Post>> getPostResponse(#RequestParam String tag, Optional<String> sortBy,
Optional<String> direction) throws InvalidSortBy {
RestTemplate postResponseTemplate = new RestTemplate();
URI postUri = UriComponentsBuilder.fromHttpUrl("urlHere")
.queryParam("tag", tag)
.queryParamIfPresent("sortBy", sortBy)
.queryParamIfPresent("direction", direction)
.build()
.toUri();
ResponseEntity<PostResponse> response = postResponseTemplate.getForEntity(postUri, PostResponse.class);
ResponseEntity<List<Post>> newResponse = responseService.createResponse(response, sortBy, direction);
return newResponse;
}
}
ive remove the url but it works for sorting the incoming data but i need to validate and throw correct errors, im just really not sure how to do it in the format required, as json, any help appreciated
First you need to handle your exception and resolve it based on error, I would suggest you raise error codes for known application exception and resolve them in your exception handler (either by using #ControllerAdvice or #RestControllerAdvice), once you have translated error code to respective message send them as json you can refer below thread for more details on following SO thread
How to throw an exception back in JSON in Spring Boot
#ExceptionHandler
#ExceptionHandler to tell Spring which of our methods should be
invoked for a given exception
#RestControllerAdvice
Using #RestControllerAdvice which contains #ControllerAdvice to
register the surrounding class as something each #Controller should be
aware of, and #ResponseBody to tell Spring to render that method's
response as JSON
Spring Boot by default returns a response body for exceptions that meets my needs out of the box:
{
"timestamp": 1587794161453,
"status": 500,
"error": "Internal Server Error",
"exception": "javax.persistence.EntityNotFoundException",
"message": "No resource exists for the given ID",
"path": "/my-resource/1"
}
However, I would like to customize the response code for different types of exceptions thrown by my application. Some of the exceptions are not ones I own, so I can't just stick a #ResponseStatus annotation on the exception class. I've tries using an #ExceptionHandler method with #ResponseStatus, but that is overwriting the response body, which I don't wish to happen. For instance, I would like to map javax.persistence.EntityNotFoundException to return status code 404.
#ExceptionHandler
#ResponseStatus(HttpStatus.NOT_FOUND)
public void handleEntityNotFoundException(EntityNotFoundException e) {
// This method returns an empty response body
}
This question is similar to mine, but it is also attempting to adjust the response body. I am hoping that there is a shorter, more idiomatic way of adjusting just the status code and not the body.
It turns out that this answer to the question I mentioned had the exact solution needed to solve this problem, even though it didn't quite fully the question asked. The trick was dropping the use of #ResponseStatus from the method, and manually setting the status on the HttpServletResponse using HttpServletResponse.sendError(). This serves the standard Spring Boot exception response, but with the updated status code.
#ExceptionHandler
public void handleEntityNotFoundException(EntityNotFoundException e, HttpServletResponse response) throws IOException {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
{
"timestamp": 1587794161453,
"status": 404,
"error": "Not Found",
"exception": "javax.persistence.EntityNotFoundException",
"message": "No resource exists for the given ID",
"path": "/my-resource/1"
}
I'm using Spring Boot 1.5.3, Spring Data REST, Spring HATEOAS, Hibernate.
Spring Data REST manage in a pretty way exceptions, returning a well formatted JSON object like this:
{
"timestamp": "2017-06-24T16:08:54.107+0000",
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : com.test.server.model.workflows.WorkSession.checkPoint -> com.test.server.model.checkpoints.CheckPoint; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved beforeQuery current operation : com.test.server.model.workflows.WorkSession.checkPoint -> com.test.server.model.checkpoints.CheckPoint",
"path": "/api/v1/workSessions/start"
}
I need to localize exception messages and I'd like to keep the same JSON format of Spring Data REST and take a look how they create the exception object.
I'm looking for the code where the exception is created in source code but I am not able to find that. Maybe ExceptionMessage is useful but it has not the structure of the object that at the end arrive to the user.
Where is the point where the exception is created?
Finally I found a useful link before I didn't see: Modify default JSON error response from Spring Boot Rest Controller.
So the object I was looking for is here: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/DefaultErrorAttributes.java
there is an answer , from useful link
As described in the documentation on error handling, you can provide
your own bean that implements ErrorAttributes to take control of the
content.
here is example from documentation :
#ControllerAdvice(basePackageClasses = FooController.class)
public class FooControllerAdvice extends ResponseEntityExceptionHandler {
#ExceptionHandler(YourException.class)
#ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
just inject Locale into handleControllerException method and MessageSource into advice , and in handleControllerException get localize exception messages that you need
I have a spring boot application.
I have a custom error controller, that is mapped to using ErrorPage mappings. The mappings are largely based on HTTP Status codes, and normally just render a HTML view appropriately.
For example, my mapping:
#Configuration
class ErrorConfiguration implements EmbeddedServletContainerCustomizer {
#Override public void customize( ConfigurableEmbeddedServletContainer container ) {
container.addErrorPages( new ErrorPage( HttpStatus.NOT_FOUND, "/error/404.html" ) )
}
And my error controller:
#Controller
#RequestMapping
public class ErrorController {
#RequestMapping( value = "/error/404.html" )
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public String pageNotFound( HttpServletRequest request ) {
"errors/404"
}
This works fine - If I just enter a random non-existent URL then it renders the 404 page.
Now, I want a section of my site, lets say /api/.. that is dedicated to my JSON api to serve the errors as JSON, so if I enter a random non-existent URL under /api/.. then it returns 404 JSON response.
Is there any standard/best way to do this? One idea I tried out was to have a #ControllerAdvice that specifically caught a class of custom API exceptions I had defined and returned JSON, and in my standard ErrorController checking the URL and throwing an apprpriate API exception if under that API URL space (but that didn't work, as the ExceptionHandler method could not be invoked because it was a different return type from the original controller method).
Is this something that has been solved?
The problem was my own fault. I was trying to work out why my #ExceptionHandler was not able to catch my exception and return JSON - As I suggested at the end of my question, I thought I was having problems because of conflicting return types - this was incorrect.
The error I was getting trying to have my exception handler return JSON was along the lines of:
"exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
"message": "Could not find acceptable representation"
I did some more digging/experimenting to try to narrow down the problem (thinking that the issue was because I was in the Spring error handling flow and in an ErrorController that was causing the problem), however the problem was just because of the content negotiation stuff Spring does.
Because my errorPage mapping in the web.xml was mapping to /error/404.html, Spring was using the suffix to resolve the appropriate view - so it then failed when I tried to return json.
I have been able to resolve the issue by changing my web.xml to /error/404 or by turning off the content negotiation suffix option.
Now, I want a section of my site, lets say /api/.. that is dedicated
to my JSON api to serve the errors as JSON, so if I enter a random
non-existent URL under /api/.. then it returns 404 JSON response.
Is there any standard/best way to do this? One idea I tried out was to
have a #ControllerAdvice that specifically caught a class of custom
API exceptions I had defined and returned JSON, and in my standard
ErrorController checking the URL and throwing an apprpriate API
exception if under that API URL space (but that didn't work, as the
ExceptionHandler method could not be invoked because it was a
different return type from the original controller method).
I think you need to rethink what you are trying to do here. According to HTTP response codes here
The 404 or Not Found error message is an HTTP standard response code
indicating that the client was able to communicate with a given
server, but the server could not find what was requested.
So when typing a random URL you may not want to throw 404 all the time. If you are trying to handle a bad request you can do something like this
#ControllerAdvice
public class GlobalExceptionHandlerController {
#ExceptionHandler(NoHandlerFoundException.class)
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
#ResponseBody
public ResponseEntity<ErrorResponse> noRequestHandlerFoundExceptionHandler(NoHandlerFoundException e) {
log.debug("noRequestHandlerFound: stacktrace={}", ExceptionUtils.getStackTrace(e));
String errorCode = "400 - Bad Request";
String errorMsg = "Requested URL doesn't exist";
return new ResponseEntity<>(new ErrorResponse(errorCode, errorMsg), HttpStatus.BAD_REQUEST);
}
}
Construct ResponseEntity that suites your need.