需求:在SpringMVC中实现全局异常捕获解析以及处理并且返回json状态码
需求分析解决:1、进入Spring-MVC配置文件配置全局异常处理复制代码
2、定义全局异常处理类
import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;import com.xxx.bean.Result;import com.xxx.excption.CustomException;import com.xxx.util.ResultUtils;/** * 全局异常处理器 * @author CatalpaFlat */public class CustomExceptionResolver implements HandlerExceptionResolver{ /**日志log*/ private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class); //系统抛出的异常 @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //handler就是处理器适配器要执行的Handler对象(只有method) //解析出异常类型。 /* 使用response返回 */ response.setStatus(HttpStatus.OK.value()); //设置状态码 response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType response.setCharacterEncoding("UTF-8"); //避免乱码 response.setHeader("Cache-Control", "no-cache, must-revalidate"); //如果该 异常类型是系统 自定义的异常,直接取出异常信息。 CustomException customException=null; try { if(ex instanceof CustomException){ customException = (CustomException)ex; //错误信息 response.getWriter().write(ResultUtils.error(customException.getCode(),ex.getMessage()).toString()); }else response.getWriter().write(ResultUtils.error(-1,ex.getMessage()).toString()); } catch (IOException e) { log.error("与客户端通讯异常:"+ e.getMessage(), e); e.printStackTrace(); } ModelAndView modelAndView=new ModelAndView(); return modelAndView; } }复制代码
3、自定义异常类CustomException
import com.xxx.enums.ResultEnum;/** * 自定义异常类型 * @author CatalpaFlat */public class CustomException extends Exception { private Integer code; public CustomException(){} public CustomException(ResultEnum resultEnum) { super((resultEnum.getMsg())); this.code = resultEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; }}复制代码
4、定义Http响应json类
/** * http请求返回的最外层 * Created by CatalpaFlat * on 2017/4/12. */public class Result{ private Integer code; private String msg; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "{\"code\": "+code+",\"msg\": \""+msg+"\",\"data\": "+data+"}"; }}复制代码
5、定义http返回json的ResulUtils
import com.xxx.bean.Result;/** * http请求返回success以及error方法封装 * Created by CatalpaFlat * on 2017/4/12. */public class ResultUtils { private static final String SUCCESS_MSG = "成功"; /** * http回调成功 * @param object * @return */ public static Result success(Object object){ Result result = new Result(); result.setCode(1); result.setMsg(SUCCESS_MSG); result.setData(object); return result; } /** * 无object返回 * @return */ public static Result success(){ return success(null); } /** * http回调错误 * @param code * @param msg * @return */ public static Result error(Integer code,String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; }}复制代码
6、定义异常类型枚举ResultEnum
/** * 枚举定义异常类型以及相对于的错误信息 * 有助于返回码的唯一性 * Created by CatalpaFlat * on 2017/4/12. */public enum ResultEnum { UNKONW_ERROR(-1,"未知错误"), SUCCESS(0,"成功"), TEST_ERRORR(100,"测试异常"); private Integer code; private String msg; ResultEnum(Integer code,String msg){ this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; }}复制代码
7、测试TestController
@Controller@RequestMapping("/teco")public class TestController { @RequestMapping(value = "/testexc",method = RequestMethod.GET) @ResponseBody public void testException() throws CustomException{ throw new CustomException(ResultEnum.TEST_ERRORR); }}复制代码
8、测试接口json返回