user1846749
user1846749

Reputation: 2535

SpringBoot rest service error handling

There are multiple ways to send custom message in error response of rest api call. Which is the best way out of these :

1.One way is to use io.swagger.annotations like @ApiResponses(value = { @ApiResponse(code = 500, message = "error message", response=ErrorDescription.class) }) above method signature.

2.Another way is to define @ControllerAdvice over global exception hanlder.

Which is the better way of two.

Thanks

Upvotes: 1

Views: 2152

Answers (1)

rieckpil
rieckpil

Reputation: 12021

Your first approach with the swagger annotation won't handle your errors in your application. It's just for documentation purposes so that you can see how your API behaves in an error case. With this annotation, you customize your swagger-ui.html page for your REST endpoint and map the error code to a specific response object and add a custom description for your clients.

To really handle e.g. exceptions with self-defined response types and message you can use @ControllerAdvice and define the result types and messages. In addition, I would also use the Swagger annotation to write some text about the error case and tell the client which response object he can expect.

The following blog post might help you for writing your @ControllerAdvice clas: http://niels.nu/blog/2016/controller-advice-exception-handlers.html

Upvotes: 2

Related Questions