Why Spring MVC does not allow to expose Model or BindingResult to an @ExceptionHandler?

后端 未结 6 2392
天命终不由人
天命终不由人 2021-02-12 18:32

Situation

I\'m trying to group the code that logs the exceptions and render a nice view in a few methods. At the moment the logic is sometime in the @RequestHand

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-12 18:58

    I ran into to same problem a while ago. The ModelMap or BindingResult are explicitly not listed as supported argument types in the JavaDocs of @ExceptionHandler, so this must have been intentional.

    I reckon the reason behind it being that throwing exceptions in general could leave your ModelMap in an inconsistent state. So depending on your situation you might consider

    • Explicitly catch the exception to tell Spring MVC that you know what you're doing (you could use the Template pattern to refactor exception handling logic into one single place)
    • If you're in control of the exception hierarchy you could hand over the BindingResult to the exception and extract it from the exception later for rendering purposes
    • Not throw an exception in the first place, but use some result code (just like BeanValidation does for example)

    HTH

提交回复
热议问题