No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an exception occurs during request processing, the outcome is still a servlet response. Somehow, the exception must be translated into a response.

Spring offers a handful of ways to translate exceptions to responses:
 Certain Spring exceptions are automatically mapped to specific HTTP status codes.
 An exception can be annotated with @ResponseStatus to map it to an HTTP status code.
 A method can be annotated with @ExceptionHandler to handle the exception.

一、利用HTTP status codes的便利性

1.让Spring自动匹配Spring的自定义异常

The exceptions in table 7.1 are usually thrown by Spring itself as the result of something going wrong in DispatcherServlet or while performing validation. For example, if DispatcherServlet can’t find a controller method suitable to handle a request,a NoSuchRequestHandlingMethodException will be thrown, resulting in a response
with a status code of 404 (Not Found).

2.自己来匹配

(1)假设consider the following request-handling method from SpittleController that could result in an HTTP 404 status (but doesn’t):

   @RequestMapping(value="/{spittleId}", method=RequestMethod.GET)
public String spittle(
@PathVariable("spittleId") long spittleId,
Model model) {
Spittle spittle = spittleRepository.findOne(spittleId);
if (spittle == null) {
throw new SpittleNotFoundException();
}
model.addAttribute(spittle);
return "spittle";
}

if findOne() returns null , then a SpittleNotFoundException is thrown. For now, SpittleNotFoundException is a simple unchecked exception that looks like this:

package spittr.web;

public class SpittleNotFoundException extends RuntimeException {}

If the spittle() method is called on to handle a request, and the given ID comes up empty, the SpittleNotFoundException will (by default) result in a response with a 500 (Internal Server Error) status code. In fact, in the event of any exception that isn’t otherwise mapped, the response will always have a 500 status code. But you can change that by mapping SpittleNotFoundException otherwise.
When SpittleNotFoundException is thrown, it’s a situation where a requested resource isn’t found. The HTTP status code of 404 is precisely the appropriate response status code when a resource isn’t found. So, let’s use @ResponseStatus to
map SpittleNotFoundException to HTTP status code 404.

 package spittr.web;

 import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Spittle Not Found")
public class SpittleNotFoundException extends RuntimeException { }

After introducing this @ResponseStatus annotation, if a SpittleNotFoundException were to be thrown from a controller method, the response would have a status code of 404 and a reason of Spittle Not Found.

运行结果:

二、在controller级别处理异常@ExceptionHandler

1.自定义异常

package spittr.web;

public class DuplicateSpittleException extends RuntimeException {

}

2.抛出异常

suppose that SpittleRepository ’s save() method throws a DuplicateSpittleException if a user attempts to create a Spittle with text identical to one they’ve already created. That means the saveSpittle() method of SpittleController might need to deal with that exception. As shown in the following listing,saveSpittle() could directly handle the exception.

 @RequestMapping(method = RequestMethod.POST)
public String saveSpittle(SpittleForm form, Model model) {
try {
spittleRepository.save(
new Spittle(null, form.getMessage(), new Date(),
form.getLongitude(), form.getLatitude()));
return "redirect:/spittles";
} catch (DuplicateSpittleException e) {
return "error/duplicate";
}
}

It works fine, but the method is a bit complex. Two paths can be taken, each with a different outcome. It’d be simpler if saveSpittle() could focus on the happy path and let some other method deal with the exception.First, let’s rip the exception-handling code out of saveSpittle() :很怀疑这里是不是会自己抛出异常DuplicateSpittleException,当保存的id重复时????

 @RequestMapping(method = RequestMethod.POST)
public String saveSpittle(SpittleForm form, Model model) {
spittleRepository.save(
new Spittle(null, form.getMessage(), new Date(),
form.getLongitude(), form.getLatitude()));
return "redirect:/spittles";
}

Now let’s add a new method to SpittleController that will handle the case where DuplicateSpittleException is thrown:

@ExceptionHandler(DuplicateSpittleException.class)
public String handleDuplicateSpittle() {
return "error/duplicate";
}

If @ExceptionHandler methods can handle exceptions thrown from any handler method in the same controller class, you might be wondering if there’s a way they can handle exceptions thrown from handler methods in any controller. As of Spring 3.2 they certainly can, but only if they’re defined in a controller advice class.

三、在application级别处理异常@ControllerAdvice

A controller advice is
any class that’s annotated with @ControllerAdvice and has one or more of the following kinds of methods:
 @ExceptionHandler -annotated
 @InitBinder -annotated
 @ModelAttribute -annotated
Those methods in an @ControllerAdvice -annotated class are applied globally across all @RequestMapping -annotated methods on all controllers in an application.
The @ControllerAdvice annotation is itself annotated with @Component . Therefore,an @ControllerAdvice -annotated class will be picked up by component-scanning, just like an @Controller -annotated class.

处理应用中所有异常

 package spittr.web;

 import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice
public class AppWideExceptionHandler { @ExceptionHandler(DuplicateSpittleException.class)
public String handleNotFound() {
return "error/duplicate";
} }

SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice的更多相关文章

  1. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver

    一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...

  2. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

  3. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)

    一.redirect为什么会丢数据? when a handler method completes, any model data specified in the method is copied ...

  4. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件

    一.用 MultipartFile 1.在html中设置<form enctype="multipart/form-data">及<input type=&quo ...

  5. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynamic、WebApplicationInitializer)

    一. 1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherSer ...

  6. SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍

    一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...

  7. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  8. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error

    一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...

  9. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)

    一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...

随机推荐

  1. Spring AOP (Spring 3.x 企业应用开发实战读书笔记第六章)

    从面相对象编程到面相切面编程,是一种代码组织方式的进化. 每一代的代码组织方式,其实是为了解决当时面对的问题.比如写编译器和写操作系统的时候的年代当然要pop,比如写界面的时候当然要oop,因为界面这 ...

  2. WPF的TextBox的焦点获取与失去焦点的死循环解决方案

    在WPF中实现一个弹出层自动获取焦点,弹出层实现是通过其UserControl的依赖属性Visibility的绑定实现的,让UserControl上的TextBox获取焦点,初始实现代码如下: pub ...

  3. Python(Django) 连接MySQL(Mac环境)

    看django的文档,详细的一塌糊涂,这对文档来时倒是好事,可是数据库连接你别一带而过啊.感觉什么都想说又啥都没说明白,最有用的一句就是推荐mysqlclient.展开一个Django项目首先就是成功 ...

  4. String Shifting

    我们规定对一个字符串的shift操作如下:略去.shift(string, x) = string(0 <= x < n). 分析:一看这题,这不很简单么,直接模拟判断,但是这套路有这么简 ...

  5. 【转载】TCP协议疑难杂症全景解析

    说明: 1).本文以TCP的发展历程解析容易引起混淆,误会的方方面面2).本文不会贴大量的源码,大多数是以文字形式描述,我相信文字看起来是要比代码更轻松的3).针对对象:对TCP已经有了全面了解的人. ...

  6. 九度OJ 1510 替换空格

    题目地址:http://ac.jobdu.com/problem.php?pid=1510 题目描述: 请实现一个函数,将一个字符串中的空格替换成"%20".例如,当字符串为We ...

  7. OpenJudge/Poj 1004 Financial Management

    1.链接地址: http://poj.org/problem?id=1004 http://bailian.openjudge.cn/practice/1004 2.题目: 总时间限制: 1000ms ...

  8. JSP九大内置对象和四个作用域

    JSP九大内置对象和四个作用域 在学习JSP的时候,首先就要先了解JSP的内置对象,什么是内置对象呢?内置对象也叫隐含对象,就是不需要预先声明就可以在脚本代码和表达式中随意使用.而这样的内置对象在JS ...

  9. debian 学习记录-2 -账户 -关机

    linux考虑系统安全设定了root账号和user账号 权限较低的user账号下,连关机命令都执行不了…… 用户切换... 用户切换1 命令su(在user账号下,即可开启root账号模式) 用户切换 ...

  10. HTMLImageElement类型的简便利用

    这个是我在复习书籍的时候看见的,当时一个同学想通过页面发送请求,但是数据量不是太大,所以用的get方式,但是页面用表单提交请求的话会让页面进行跳转,当时我在网上查了一点资料,发现基本上都是通过ajax ...