8

过去几个月我一直在用 Spring + hibernate 开发一个 web 应用程序。我一直严重缺少的是异常处理。

我想知道处理异常的最佳方法和实践?我有一些问题无法涵盖异常处理的所有方面,例如:

1.是否做checked or unchecked Exception?如何决定?

2.Controller中产生的异常如何处理和处理。

3.Service层和DAO层产生的异常怎么办?应该只在该层处理还是应该转移到控制器层?

4.既然可能有很多例外,我该如何准备处理将来可能出现的那些?

5.如何向UI或浏览器显示相关消息?

请建议或提供好的博客链接?

4

2 回答 2

12
  1. 如果有合理的期望客户端可以处理异常并从异常中恢复,则使用 Checked Exceptions,否则使用 Unchecked(您将主要使用 unchecked)。
  2. 使用@ExceptionHandler方法上的注解来处理@RequestMapping方法产生的异常。
  3. throw它们发送给控制器,以便它可以决定最佳响应,除非服务方法实际上可以从异常中恢复并正常进行处理。
  4. 创建自定义异常和throw那些代替(您可以将实际异常作为原因传递,即throw new MyCustomException("my message", e)
  5. 您的@ExceptionHandler方法可以决定返回给用户的视图,或者您可以在您的web.xml
于 2013-08-29T11:59:38.907 回答
5
  1. In general don't use checked exceptions, you don't want to use exception for flow control, next to that most exceptions are unrecoverable so then what are you going to do? See this related answer.

  2. Regarding exception handling, spring has the HandlerExceptionResolver for that. You can use this for general exception handling. For more fine grained control you can annotate methods in your controller with @ExceptionHandler those will handle exceptions occuring from that controller only. (Although with the new @ControllerAdvice you can also register global @ExceptionHandler methods.

  3. In some cases you might want to catch the exception in your controller and handle them inside the controller (i.e. show a warning to the user for instance).

As a last resort you can always configure the error-page in your web.xml for very generic and broad exception handling.

For more information you might want to check the exception handling section in the Spring Reference Guide.

于 2013-08-29T12:07:42.520 回答