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

后端 未结 6 1094
时光说笑
时光说笑 2021-02-12 18:41

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 19:13

    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

提交回复
热议问题