Reputation: 2424
I have a simple rest endpoint as follows:
@RequestMapping(method = RequestMethod.GET, value = "/error")
public ResponseEntity<String> genericErrorHandler() {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("");
}
The purpose of this is to make it as a default error response for my REST API. However, this endpoint is never recognized by Spring. It is never called. The problem is the path itself. It is "/error". If I change it to anything else, like "/foo", it will work.
According to this docs:
At start-up, Spring Boot tries to find a mapping for /error. By convention, a URL ending in /error maps to a logical view of the same name: error. If no mapping from /error to a View can be found, Spring Boot defines its own fall-back error page - the so-called “Whitelabel Error Page” (a minimal page with just the HTTP status information and any error details, such as the message from an uncaught exception).
So. whenever an exception is thrown and it is not handled by any @ExceptionHandler
annotated method, then Spring boot will call this endpoint (/error
). I am simply trying to get rid of the default "Whitelabel Error Page" that spring boot provides, and use this endpoint instead. Am I misunderstanding the purpose of the /error page? Or what is it that I am doing incorrectly?
================UPDATE==================
So, I was able to get the /error endpoint to work by forcing the class, which contains the /error endpoint, to implement interface ErrorController, as suggested in the possible duplicate post
However, after this, ALL my endpoints get rerouted to this /error. Meaning, all things that worked before, like /user/1, or /orders, now fall back to /error. Do you have any idea what went wrong here?
Here is where /error is defined:
@RestController
@RequestMapping("/error")
public class FallbackErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> genericErrorHandler() {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("A fake error");
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}
Upvotes: 3
Views: 11308
Reputation: 121
This is what worked for me:
@Override
public String getErrorPath() {
return PATH;
}
Returns the path of the error page. i.e.
private static final String PATH = "/error";
now it is redirected to the /error route.
Sequencially,
@Controller
@RequestMapping(value="/")
public class HomeController implements ErrorController{
private static final String PATH = "/error";
@GetMapping(value=PATH)
public String error(Model model) {
return "error/error404";
}
@Override
public String getErrorPath() {
return PATH;
}
}
Upvotes: 2