问题
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:
- Create a controller that implements
ErrorController
and overrides itsgetErrorPath()
method. - 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