本文介绍了我应该在Spring MVC中将异常处理放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索了很多,发现几乎所有示例都在具有自己的Exception Handler的Controller中使用了异常处理.我一直认为这应该在程序的服务层上完成.如果没有,我真的不明白创建单独的服务层的原因.

此外,如果我在Controller中实现异常处理,是否意味着我必须在所有先前的层中抛出异常?

解决方案

除非可以从错误情况中恢复,否则必须让异常一直弹出到控制器,以便将它们转换为HTTP错误并将该错误发回客户端.

由于(例如)无效输入"将必须作为 400 Bad Request HTTP状态代码返回给客户端,因此很明显,只有Spring MVC控制器能够做到这一点./p>

这就是为什么为不同类型的错误定义错误处理方法并将异常映射到状态码可能是一个好主意的原因.这种映射的一个示例是:

  • IllegalArgumentException -> 400 Bad Request
  • IllegalStateException -> 503 Service Unavailable
  • AuthenticationException -> 401未经授权
  • AccessDeniedException | SecurityException -> 403 Forbidden
  • UnsupportedOperationException -> 501未实现
  • Throwable (其他)-> 500内部服务器错误

服务层应仅处理 recoverable 异常,并且应将低级异常转换(包装)为一组明确定义的一致异常(例如 catch(FileNotFoundException e)代码>-> 引发新的IllegalStateException(e)).

因此它不会变得无用.此外,该层应包含所有业务逻辑",并让Spring MVC(或任何Web框架)控制器仅专注于HTTP.

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?

解决方案

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.

这篇关于我应该在Spring MVC中将异常处理放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:32