Where should I put my exception handling in Spring MVC?

为君一笑 提交于 2021-01-28 18:33:53

问题


I googled a lot and almost all examples I found used exception handling in Controller with own Exception Handler. I always thought this should be done on service layer of program. If not, I really don't understand the reason to create separate service layer.

Also, if I implement my exception handling in Controller, does it mean that I must throw exception in all the previous layers?


回答1:


Unless you can recover from an error condition, you'll have to let your exceptions pop all the way up to the controller, so that you can convert them into HTTP errors and signal that error back to the client.

Since (e.g.) "invalid input" will have to get back to the client as a 400 Bad Request HTTP status code, it's obvious that only the Spring MVC controller is able to do that.

That's why it may be a good idea to define error handling methods for different kinds of errors and map exceptions to status codes. An example of such a mapping would be:

  • IllegalArgumentException -> 400 Bad Request
  • IllegalStateException -> 503 Service Unavailable
  • AuthenticationException -> 401 Unauthorized
  • AccessDeniedException|SecurityException -> 403 Forbidden
  • UnsupportedOperationException -> 501 Not Implemented
  • Throwable (anything else) -> 500 Internal Server Error

The service layer should only handle recoverable exceptions and it should translate (wrap) low-level exceptions into a coherent set of well-defined exceptions (e.g. catch (FileNotFoundException e) -> throw new IllegalStateException(e)).

So it doesn't become useless. Besides, this layer should contain all the "business logic" and let the Spring MVC (or whatever web framework) controller focus only on HTTP stuff.



来源:https://stackoverflow.com/questions/33966211/where-should-i-put-my-exception-handling-in-spring-mvc

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