---
title: "Spring 注解学习手札（八）补遗——@ExceptionHandler"
author: "wxyfighting"
date: "2013-06-12T09:12:00Z"
tags: []
slug: "spring-exceptionhandler"
draft: false
lastmod: "2013-06-12T14:32:14Z"
id: 1885594
url: "https://wxyfighting.iteye.com/blog/1885594"
---

Spring注解，改变了我的开发思路。前段时间，用@RequestBody，@ResponseBody，不费吹灰之力就解决了JSon自动绑定。接着就发现，如果遇到RuntimeException，需要给出一个默认返回JSON。

以前都是用SimpleMappingExceptionResolver拦截实现，今天偶尔看下资料，@ExceptionHandler，就把这个异常给拦截了，太方便了！

直接上代码：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. @Controller
02. publicclassAccessController{
03. /\**
04. \*异常页面控制
05. \*
06. \*@paramruntimeException
07. \*@return
08. \*/
09. @ExceptionHandler(RuntimeException.class)
10. public@ResponseBody
11. Map&lt;String,Object&gt;runtimeExceptionHandler(RuntimeExceptionruntimeException){
12. logger.error(runtimeException.getLocalizedMessage());
13. Mapmodel=newTreeMap();
14. model.put("status",false);
15. returnmodel;
16. }
17. }

当这个Controller中任何一个方法发生异常，一定会被这个方法拦截到。然后，输出日志。封装Map并返回，页面上得到status为false。就这么简单。![](http://snowolf.iteye.com/images/smiles/icon_idea.gif)

或者这个有些有些复杂，来个简单易懂的，上代码：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. @Controller
02. publicclassAccessController{
03. /\**
04. \*异常页面控制
05. \*
06. \*@paramruntimeException
07. \*@return
08. \*/
09. @ExceptionHandler(RuntimeException.class)
10. publicStringruntimeExceptionHandler(RuntimeExceptionruntimeException,
11. ModelMapmodelMap){
12. logger.error(runtimeException.getLocalizedMessage());
13. modelMap.put("status",IntegralConstant.FAIL\_STATUS);
14. return"exception";
15. }
16. }