springmvc 通过异常增强返回给客户端统一格式
在springmvc开发中,我们经常遇到这样的问题;逻辑正常执行时返回客户端指定格式的数据,比如json,但是遇NullPointerException空指针异常,NoSuchMethodException调用的方法不存在异常,返回给客户端的是服务端异常堆栈信息,导致客户端不能正常解析数据;这明显不是我们想要的。
幸好从spring3.2提供的新注解@ControllerAdvice,从名字上可以看出大体意思是控制器增强。原理是使用AOP对Controller控制器进行增强(前置增强、后置增强、环绕增强,AOP原理请自行查阅);那么我没可以自行对控制器的方法进行调用前(前置增强)和调用后(后置增强)的处理。
spring提供了@ExceptionHandler异常增强注解。程序如果在执行控制器方法前或执行时抛出异常,会被@ExceptionHandler注解了的方法处理。
配置applicationContext-mvc.xml:
<!-- 使用Annotation自动注册Bean,扫描@Controller和@ControllerAdvice-->
<context:component-scan base-package="com.drskj.apiservice" use-default-filters="false">
<!-- base-package 如果多个,用“,”分隔 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<!--控制器增强,使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常-->
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
全局异常处理类:
package com.drskj.apiservice.handler; import java.io.IOException; import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import com.drskj.apiservice.common.utils.ReturnFormat;
/**
* 异常增强,以JSON的形式返回给客服端
* 异常增强类型:NullPointerException,RunTimeException,ClassCastException,
NoSuchMethodException,IOException,IndexOutOfBoundsException
以及springmvc自定义异常等,如下:
SpringMVC自定义异常对应的status code
Exception HTTP Status Code
ConversionNotSupportedException 500 (Internal Server Error)
HttpMessageNotWritableException 500 (Internal Server Error)
HttpMediaTypeNotSupportedException 415 (Unsupported Media Type)
HttpMediaTypeNotAcceptableException 406 (Not Acceptable)
HttpRequestMethodNotSupportedException 405 (Method Not Allowed)
NoSuchRequestHandlingMethodException 404 (Not Found)
TypeMismatchException 400 (Bad Request)
HttpMessageNotReadableException 400 (Bad Request)
MissingServletRequestParameterException 400 (Bad Request)
*
*/
@ControllerAdvice
public class RestExceptionHandler{
//运行时异常
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public String runtimeExceptionHandler(RuntimeException runtimeException) { return ReturnFormat.retParam(1000, null);
} //空指针异常
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public String nullPointerExceptionHandler(NullPointerException ex) {
ex.printStackTrace();
return ReturnFormat.retParam(1001, null);
}
//类型转换异常
@ExceptionHandler(ClassCastException.class)
@ResponseBody
public String classCastExceptionHandler(ClassCastException ex) {
ex.printStackTrace();
return ReturnFormat.retParam(1002, null);
} //IO异常
@ExceptionHandler(IOException.class)
@ResponseBody
public String iOExceptionHandler(IOException ex) {
ex.printStackTrace();
return ReturnFormat.retParam(1003, null);
}
//未知方法异常
@ExceptionHandler(NoSuchMethodException.class)
@ResponseBody
public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
ex.printStackTrace();
return ReturnFormat.retParam(1004, null);
} //数组越界异常
@ExceptionHandler(IndexOutOfBoundsException.class)
@ResponseBody
public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
ex.printStackTrace();
return ReturnFormat.retParam(1005, null);
}
//400错误
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public String requestNotReadable(HttpMessageNotReadableException ex){
System.out.println("400..requestNotReadable");
ex.printStackTrace();
return ReturnFormat.retParam(400, null);
}
//400错误
@ExceptionHandler({TypeMismatchException.class})
@ResponseBody
public String requestTypeMismatch(TypeMismatchException ex){
System.out.println("400..TypeMismatchException");
ex.printStackTrace();
return ReturnFormat.retParam(400, null);
}
//400错误
@ExceptionHandler({MissingServletRequestParameterException.class})
@ResponseBody
public String requestMissingServletRequest(MissingServletRequestParameterException ex){
System.out.println("400..MissingServletRequest");
ex.printStackTrace();
return ReturnFormat.retParam(400, null);
}
//405错误
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
@ResponseBody
public String request405(){
System.out.println("405...");
return ReturnFormat.retParam(405, null);
}
//406错误
@ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
@ResponseBody
public String request406(){
System.out.println("404...");
return ReturnFormat.retParam(406, null);
}
//500错误
@ExceptionHandler({ConversionNotSupportedException.class,HttpMessageNotWritableException.class})
@ResponseBody
public String server500(RuntimeException runtimeException){
System.out.println("500...");
return ReturnFormat.retParam(406, null);
}
}
以上包括了常见的服务端异常类型,@ResponseBody表示以json格式返回客户端数据。我们也可以自定义异常类(这里我把它叫做MyException)并且继承RunTimeException,并且在全局异常处理类新增一个方法来处理异常,使用@ExceptionHandler(MyException.class)注解在方法上实现自定义异常增强。
格式化response数据类ReturnFormat:
package com.drskj.apiservice.common.utils; import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.alibaba.fastjson.JSON;import com.google.common.collect.Maps;
//格式化返回客户端数据格式(json)
public class ReturnFormat {
private static Map<String,String>messageMap = Maps.newHashMap();
//初始化状态码与文字说明
static {
messageMap.put("0", ""); messageMap.put("400", "Bad Request!");
messageMap.put("401", "NotAuthorization");
messageMap.put("405", "Method Not Allowed");
messageMap.put("406", "Not Acceptable");
messageMap.put("500", "Internal Server Error"); messageMap.put("1000", "[服务器]运行时异常");
messageMap.put("1001", "[服务器]空值异常");
messageMap.put("1002", "[服务器]数据类型转换异常");
messageMap.put("1003", "[服务器]IO异常");
messageMap.put("1004", "[服务器]未知方法异常");
messageMap.put("1005", "[服务器]数组越界异常");
messageMap.put("1006", "[服务器]网络异常"); messageMap.put("1010", "用户未注册");
messageMap.put("1011", "用户已注册");
messageMap.put("1012", "用户名或密码错误");
messageMap.put("1013", "用户帐号冻结");
messageMap.put("1014", "用户信息编辑失败");
messageMap.put("1015", "用户信息失效,请重新获取"); messageMap.put("1020", "验证码发送失败");
messageMap.put("1021", "验证码失效");
messageMap.put("1022", "验证码错误");
messageMap.put("1023", "验证码不可用");
messageMap.put("1029", "短信平台异常"); messageMap.put("1030", "周边无店铺");
messageMap.put("1031", "店铺添加失败");
messageMap.put("1032", "编辑店铺信息失败");
messageMap.put("1033", "每个用户只能添加一个商铺");
messageMap.put("1034", "店铺不存在"); messageMap.put("1040", "无浏览商品");
messageMap.put("1041", "添加失败,商品种类超出上限");
messageMap.put("1042", "商品不存在");
messageMap.put("1043", "商品删除失败"); messageMap.put("2010", "缺少参数或值为空"); messageMap.put("2029", "参数不合法");
messageMap.put("2020", "无效的Token");
messageMap.put("2021", "无操作权限");
messageMap.put("2022", "RSA解密失败,密文数据已损坏");
messageMap.put("2023", "请重新登录");
}
public static String retParam(int status,Object data) {
OutputJson json = new OutputJson(status, messageMap.get(String.valueOf(status)), data);
return json.toString();
}
}
返回格式实体类OutPutJson;这里用到了知名的fastjson将对象转json:
package com.drskj.apiservice.common.utils;
import java.io.Serializable;
import com.alibaba.fastjson.JSON;
public class OutputJson implements Serializable{
/**
* 返回客户端统一格式,包括状态码,提示信息,以及业务数据
*/
private static final long serialVersionUID = 1L;
//状态码
private int status;
//必要的提示信息
private String message;
//业务数据
private Object data;
public OutputJson(int status,String message,Object data){
this.status = status;
this.message = message;
this.data = data;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String toString(){
if(null == this.data){
this.setData(new Object());
}
return JSON.toJSONString(this);
}
}
实例:CodeController继承自BaseController,有一个sendMessage方法调用Service层发送短信验证码;
1.如果客户端请求方式为非POST,否则抛出HttpMediaTypeNotSupportedException异常;
2.如果username、forType或userType没传,则抛出MissingServletRequestParameterException异常;
3.如果springmvc接收无法进行类型转换的字段,会报TypeMismatchException异常;
.....
大部分的请求异常,springmvc已经为我们定义好了,为我们开发restful应用提高了测试效率,方便排查问题出在哪一环节。
@RestController
@RequestMapping("/api/v1/code")
public class CodeController extends BaseController {
@Autowired
private CodeService codeService;
/**
* 发送短信
* @param username 用户名
* @param type register/backpwd
* @return
* status: 0 2010 2029 1011 1010 1006 1020
*/
@RequestMapping(value="/sendMessage",method=RequestMethod.POST,produces="application/json")
public String sendMessage(@RequestParam(value="username",required=true)String username,
@RequestParam(value="forType",required=true)String forType,
@RequestParam(value="userType",required=true)String userType){
if(null == username || "".equals(username)){
return retContent(2010, null);
}
if(!"user".equals(userType) && !"merchant".equals(userType)){
return retContent(2029, null);
}
if(!"register".equals(forType) && !"backpwd".equals(forType)){
return retContent(2029, null);
}
return codeService.sendMessage(username, forType, userType);
}
}
public abstract class BaseController {
protected String retContent(int status,Object data) {
return ReturnFormat.retParam(status, data);
}
}
最终,不管是正常的业务逻辑还是服务端异常,都会调用ReturnFormat.retParam(int status,Object data)方法返回格式统一的数据。
springmvc 通过异常增强返回给客户端统一格式的更多相关文章
- [转]SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意
一.SpringMVC使用@ResponseBody时返回json的日期格式 前提了解: @ResponseBody 返回json字符串的核心类是org.springframework.http.co ...
- SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意
一.SpringMVC使用@ResponseBody时返回json的日期格式 前提了解: @ResponseBody 返回json字符串的核心类是org.springframework.http.co ...
- springmvc全局异常后返回JSON异常数据
转自:http://www.cnblogs.com/exmyth/p/5601288.html (1)自定义或者使用spring自带的各种异常处理器 例如spring基于注解的异常解析器Annotat ...
- SpringMVC使用@ResponseBody时返回json的日期格式及可能产生的问题
http://blog.csdn.net/z69183787/article/details/40375831 遇到的问题: 1 条件: 1.1.表单里有两个时间参数,都是作为隐藏项随表单一起提交: ...
- WCF实现将服务器端的错误信息返回到客户端
转载:http://www.cnblogs.com/zeroone/articles/2299001.html http://www.it165.net/pro/html/201403/11033.h ...
- SpringMVC全局异常统一处理
SpringMVC全局异常统一处理以及处理顺序最近在使用SpringMVC做全局异常统一处理的时候遇到的问题,就是想把ajax请求和普通的网页请求分开返回json错误信息或者跳转到错误页. 在实际做的 ...
- springmvc的异常统一处理
在项目实际开发中,异常的统一处理是一个常态.假如不使用异常统一处理,我们往往需要在service层中捕获异常,并且根据不同的异常在result中的设置不同的code并给予相应的提示.这样可能会导致不同 ...
- 【swagger】2.swagger提供开发者文档--返回统一格式篇【spring mvc】【spring boot】
接着上一篇来说, 不管正常返回结果还是后台出现异常,应该返回给前台统一的响应格式. 所以这一篇就为了应对解决这个问题. ======================================== ...
- RestFul API 统一格式返回 + 全局异常处理
一.背景 在分布式.微服务盛行的今天,绝大部分项目都采用的微服务框架,前后端分离方式.前端和后端进行交互,前端按照约定请求URL路径,并传入相关参数,后端服务器接收请求,进行业务处理,返回数据给前端. ...
随机推荐
- asp.net mvc 应用Bundle(捆绑和微小)压缩技术 启用 BundleConfig 配置web.config
从MVC4开始,我们就发现,项目中对Global.asax进行了优化,将原来在MVC3中使用的代码移到了 [App_Start]文件夹下,而Global.asax只负责初始化.其中的BundleCon ...
- Cookie/Session机制
这些都是基础知识,不过有必要做深入了解.先简单介绍一下. 二者的定义: 当你在浏览网站的时候,WEB 服务器会先送一小小资料放在你的计算机上,Cookie 会帮你在网站上所打的文字或是一些选择, 都纪 ...
- 开篇:IT软件人员学习的书籍 - IT软件人员书籍系列文章
读书是一件快乐的事情. 读书能够增长知识,了解社会,了解人类的思想,继而转换成智慧.无论是什么人,都需要读书,多读书,读好书,同时也要把书中的精髓记录下来,一个是当做读后感,一个是为以后如果忘记了回头 ...
- asp.net之treeview无法显示树结点图标(IP与域名的表现竟不一样)
背景 今天接到客户的电话,说部署上去的项目树型的treeview无法正常显示,显示成了好几个大红叉.如: 排查 于是我通过远程登录到服务器,在本地测试了一会发现没有这个问题存在,无论是通过IP ...
- Linux老是提示compat-libstdc++ is not installed的原因
在一Linux服务器上检查是否安装了一些包时,遇到老是提示"package compat-libstdc++ is not installed" [root@DB-Server ~ ...
- SQL Server:“数据收缩”详解
1. 数据库的相关属性 在MS中创建数据库时会为数据库分配初始的大小(如下图:数据库和日志两个文件),随着数据库的使用文件会逐渐增大.数据库文件大小的增加有两种方式: 自动增长:在自动增长中可以设置每 ...
- Java的String.valueOf 转换 与、空串+类型变量转换与封装类(Integer)的toString方式转换比较。
1.空串+类型变量方式转换 int i=20; String s=""+i; 这种方式实际上经过了两个步骤,首先进行了i.ToString()把 i 转换为 字符串,然后再进行加法 ...
- Linux 下从头再走 GTK+-3.0 (三)
之前我们为窗口添加了一个按钮,接下来让这个按钮丰富一点.并给窗口加上图标. 首先创建 example3,c 的源文件. #include <gtk/gtk.h> static void a ...
- IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇)
IO - 同步,异步,阻塞,非阻塞 (亡羊补牢篇) 当你发现自己最受欢迎的一篇blog其实大错特错时,这绝对不是一件让人愉悦的事. <IO - 同步,异步,阻塞,非阻塞 >是我在开始学习e ...
- [译] OpenStack Kilo 版本中 Neutron 的新变化
OpenStack Kilo 版本,OpenStack 这个开源项目的第11个版本,已经于2015年4月正式发布了.现在是个合适的时间来看看这个版本中Neutron到底发生了哪些变化了,以及引入了哪些 ...