How to add model attributes to the default error p

2019-08-29 02:45发布

问题:

What is the best way to handle default page not found error when a user requests a url that doesn't have any mapping in the application (e.g. a url like /aaa/bbb that there is no mapping for it in the application) while be able to add model attributes to the page?

回答1:

There is some anserws in SO but those have caused me other problems and more importantly they don't state how to add model attributes to the error page. The best solution I have found is this:

  1. Create a controller that implements ErrorController and overrides its getErrorPath() method.
  2. In that controller create a handler method annotated with @RequestMapping("/error")

It's in this method that you can add whatever model attributes you want and return whatever view name you want:

@Controller
public class ExceptionController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public String handleError(Model model) {
        model.addAttribute("message", "An exception occurred in the program");
        return "myError";
    }
}

Now if you want to handle other specific exceptions you can create @ExceptionHandler methods for them:

@ExceptionHandler(InvalidUsernameException.class)
public String handleUsernameError(Exception exception, Model model) {
    model.addAttribute("message", "Invalid username");
    return "usernameError";
}

Notes:

  • If you add specific exception handlers in the class, don't forget to annotate the controller with @ControllerAdvice (along with the @Controller)

  • The overridden getErrorPath() method can return any path you want as well as /error.