Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot 404 error custom error response ReST

I'm using Spring boot for hosting a REST API. Instead of having the standard error response I would like to always send a JSON response even if a browser is accessing the URL and as well a custom data structure.

I can do this with @ControllerAdvice and @ExceptionHandler for custom exceptions. But I can't find any good ways of doing this for standard and handled errors like 404 and 401.

Are there any good patterns of how to do this?

like image 644
Markus Avatar asked Jun 18 '15 14:06

Markus


People also ask

How do I send a custom error message in REST API Spring boot?

The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.

Why does Spring boot say 404 error?

We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web. xml.


1 Answers

For those Spring Boot 2 users who don't wanna use @EnableWebMvc

application.properties

server.error.whitelabel.enabled=false spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false 

ControllerAdvice

@RestControllerAdvice public class ExceptionResolver {      @ExceptionHandler(NoHandlerFoundException.class)     @ResponseStatus(HttpStatus.NOT_FOUND)     public HashMap<String, String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) {         HashMap<String, String> response = new HashMap<>();         response.put("status", "fail");         response.put("message", e.getLocalizedMessage());         return response;     } } 

Source

like image 172
fightlight Avatar answered Sep 26 '22 17:09

fightlight