How to add model attributes to the default error page

纵然是瞬间 提交于 2020-01-06 07:11:06

问题


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.



来源:https://stackoverflow.com/questions/50968462/how-to-add-model-attributes-to-the-default-error-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!