package cn.com.servyou.gxdqy.exceptions; import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
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 java.io.IOException;
import java.util.Map; /**
* @author : hao
* @project : daieweb
* @description :
* @time : 2018/5/30 18:25
*/
@ControllerAdvice
public class WebExceptionHandler { private static Logger logger = Logger.getLogger(WebExceptionHandler.class); private static Map<String, String> messageMap = Maps.newHashMap(); static { messageMap.put("runtimeException", "运行时异常");
messageMap.put("nullPointerException", "空指针异常");
messageMap.put("classCastException", "类型转换异常");
messageMap.put("iOException", "IO异常");
messageMap.put("noSuchMethodException", "未知方法异常");
messageMap.put("indexOutOfBoundsException", "数组越界异常");
messageMap.put("httpMessageNotReadableException", "参数格式错误或没有无参构造器");
messageMap.put("typeMismatchException", "参数类型异常");
messageMap.put("missingServletRequestParameterException", "缺少参数异常");
messageMap.put("httpRequestMethodNotSupportedException", "请求类型异常");
messageMap.put("httpMediaTypeNotAcceptableException", "请求后缀异常或MediaType前后不匹配");
messageMap.put("conversionNotSupportedException", "类型注入可能非接口异常");
messageMap.put("httpMessageNotWritableException", "结果转换异常可能存在bean属性为空");
} @ExceptionHandler(RuntimeException.class)
@ResponseBody
public ResponseResult<Object> runtimeExceptionHandler(RuntimeException runtimeException) {
logger.error(runtimeException.getMessage(), runtimeException);
return RestResultGenerator.genResult(messageMap.get("runtimeException") + ":" + runtimeException.getMessage());
} @ExceptionHandler(NullPointerException.class)
@ResponseBody
public ResponseResult<Object> nullPointerExceptionHandler(NullPointerException nullPointerException) {
logger.error(nullPointerException.getMessage(), nullPointerException);
return RestResultGenerator.genResult(messageMap.get("nullPointerException") + ":" + nullPointerException.getMessage());
} @ExceptionHandler(ClassCastException.class)
@ResponseBody
public ResponseResult<Object> classCastExceptionHandler(ClassCastException classCastException) {
logger.error(classCastException.getMessage(), classCastException);
return RestResultGenerator.genResult(messageMap.get("classCastException") + ":" + classCastException.getMessage());
} @ExceptionHandler(IOException.class)
@ResponseBody
public ResponseResult<Object> iOExceptionHandler(IOException iOException) {
logger.error(iOException.getMessage(), iOException);
return RestResultGenerator.genResult(messageMap.get("iOException") + ":" + iOException.getMessage());
} @ExceptionHandler(NoSuchMethodException.class)
@ResponseBody
public ResponseResult<Object> noSuchMethodExceptionHandler(NoSuchMethodException noSuchMethodException) {
logger.error(noSuchMethodException.getMessage(), noSuchMethodException);
return RestResultGenerator.genResult(messageMap.get("noSuchMethodException") + ":" + noSuchMethodException.getMessage());
} @ExceptionHandler(IndexOutOfBoundsException.class)
@ResponseBody
public ResponseResult<Object> indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException indexOutOfBoundsException) {
logger.error(indexOutOfBoundsException.getMessage(), indexOutOfBoundsException);
return RestResultGenerator.genResult(messageMap.get("indexOutOfBoundsException") + ":" + indexOutOfBoundsException.getMessage());
} @ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public ResponseResult<Object> requestNotReadable(HttpMessageNotReadableException httpMessageNotReadableException) {
logger.error(httpMessageNotReadableException.getMessage(), httpMessageNotReadableException);
return RestResultGenerator.genResult(messageMap.get("httpMessageNotReadableException") + ":" + httpMessageNotReadableException.getMessage());
} @ExceptionHandler({TypeMismatchException.class})
@ResponseBody
public ResponseResult<Object> requestTypeMismatch(TypeMismatchException typeMismatchException) {
logger.error(typeMismatchException.getMessage(), typeMismatchException);
return RestResultGenerator.genResult(messageMap.get("typeMismatchException") + ":" + typeMismatchException.getMessage());
} @ExceptionHandler({MissingServletRequestParameterException.class})
@ResponseBody
public ResponseResult<Object> requestMissingServletRequest(MissingServletRequestParameterException missingServletRequestParameterException) {
logger.error(missingServletRequestParameterException.getMessage(), missingServletRequestParameterException);
return RestResultGenerator.genResult(messageMap.get("missingServletRequestParameterException") + ":" + missingServletRequestParameterException.getMessage());
} @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
@ResponseBody
public ResponseResult<Object> request405(HttpRequestMethodNotSupportedException httpRequestMethodNotSupportedException) {
logger.error(httpRequestMethodNotSupportedException.getMessage(), httpRequestMethodNotSupportedException);
return RestResultGenerator.genResult(messageMap.get("httpRequestMethodNotSupportedException") + ":" + httpRequestMethodNotSupportedException.getMessage());
} @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
@ResponseBody
public ResponseResult<Object> request406(HttpMediaTypeNotAcceptableException httpMediaTypeNotAcceptableException) {
logger.error(httpMediaTypeNotAcceptableException.getMessage(), httpMediaTypeNotAcceptableException);
return RestResultGenerator.genResult(messageMap.get("httpMediaTypeNotAcceptableException") + ":" + httpMediaTypeNotAcceptableException.getMessage());
} @ExceptionHandler({ConversionNotSupportedException.class})
@ResponseBody
public ResponseResult<Object> server500(ConversionNotSupportedException conversionNotSupportedException) {
logger.error(conversionNotSupportedException.getMessage(), conversionNotSupportedException);
return RestResultGenerator.genResult(messageMap.get("conversionNotSupportedException") + ":" + conversionNotSupportedException.getMessage());
} @ExceptionHandler({HttpMessageNotWritableException.class})
@ResponseBody
public ResponseResult<Object> server500(HttpMessageNotWritableException httpMessageNotWritableException) {
logger.error(httpMessageNotWritableException.getMessage(), httpMessageNotWritableException);
return RestResultGenerator.genResult(messageMap.get("conversionNotSupportedException") + ":" + httpMessageNotWritableException.getMessage());
}
}

异常结果封装:

import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class RestResultGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(RestResultGenerator.class); public RestResultGenerator() {
} public static <T> ResponseResult<List<T>> genResult(PagerBean<T> data) {
ResponseResult result = new ResponseResult();
result.setSuccess(true);
result.setData(data.getData());
result.setTotal(data.getTotal());
result.setPageIndex(data.getPageIndex());
result.setPageSize(data.getPageSize());
return result;
} public static <T> ResponseResult<T> genResult(T data, String message) {
ResponseResult result = new ResponseResult();
result.setSuccess(true);
result.setData(data);
result.setMessage(message);
return result;
} public static <T> ResponseResult<T> genResult(String error) {
ResponseResult result = new ResponseResult();
if(StringUtils.isEmpty(error)) {
result.setSuccess(true);
} else {
result.setSuccess(false);
} result.setError(error);
return result;
}
}

  

返回结果bean:

@JsonInclude(Include.NON_EMPTY) //为空的属性不参与序列化
public class ResponseResult<T> {
private boolean success = true;
private String error;
private T data;
private String message;
private long total;
private int pageSize;
private int pageIndex; public ResponseResult() {
} public long getTotal() {
return this.total;
} public void setTotal(long total) {
this.total = total;
} public int getPageSize() {
return this.pageSize;
} public void setPageSize(int pageSize) {
this.pageSize = pageSize;
} public int getPageIndex() {
return this.pageIndex;
} public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
} public String getError() {
return this.error;
} public void setError(String error) {
this.error = error;
} public T getData() {
return this.data;
} public void setData(T data) {
this.data = data;
} public String getMessage() {
return this.message;
} public void setMessage(String message) {
this.message = message;
} public boolean isSuccess() {
return this.success;
} public void setSuccess(boolean success) {
this.success = success;
}
}

  

SpringMvc 全局异常处理器定义,友好的返回后端错误信息的更多相关文章

  1. springmvc中拦截器与springmvc全局异常处理器的问题

    最近在做一个练手的小项目, 系统架构中用了springmvc的全局异常处理器, 做了系统的统一异常处理. 后来加入了springmvc的拦截器, 为了一些需求, 在拦截器中的 preHandle 方法 ...

  2. springmvc全局异常后返回JSON异常数据

    转自:http://www.cnblogs.com/exmyth/p/5601288.html (1)自定义或者使用spring自带的各种异常处理器 例如spring基于注解的异常解析器Annotat ...

  3. SpringMVC实现全局异常处理器 (转)

    出处:  SpringMVC实现全局异常处理器 我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发.测试通过手 ...

  4. 关于SpringMVC的全局异常处理器

    近几天又温习了一下SpringMVC的运行机制以及原理 我理解的springmvc,是设计模式MVC中C层,也就是Controller(控制)层,常用的注解有@Controller.@RequestM ...

  5. 基于SpringMVC的全局异常处理器介绍(转)

    近几天又温习了一下SpringMVC的运行机制以及原理 我理解的springmvc,是设计模式MVC中C层,也就是Controller(控制)层,常用的注解有@Controller.@RequestM ...

  6. 从源码看全局异常处理器@ExceptionHandler&@ExceptionHandler的生效原理

    1.开头在前 日常开发中,几乎我们的项目都会用到异常处理器,我们通常会定制属于自己的异常处理器,来处理项目中大大小小.各种各样的异常.配置异常处理器目前最常用的方式应该是使用@ControllerAd ...

  7. 【spring】-- springboot配置全局异常处理器

    一.为什么要使用全局异常处理器? 什么是全局异常处理器? 就是把错误异常统一处理的方法. 应用场景: 1.当你使用jsr303参数校验器,如果参数校验不通过会抛异常,而且无法使用try-catch语句 ...

  8. Spring Boot 中全局异常处理器

    Spring Boot 中全局异常处理器,就是把错误异常统一处理的方法.等价于Springmvc中的异常处理器. 步骤一:基于前面的springBoot入门小demo修改 步骤二:修改HelloCon ...

  9. SSM之全局异常处理器

    1. 异常处理思路 首先来看一下在springmvc中,异常处理的思路:   如上图所示,系统的dao.service.controller出现异常都通过throws Exception向上抛出,最后 ...

随机推荐

  1. Struts2自定义标签3模仿原有的s:if s:elseif s:else自定义自己的if elsif else

    第一步:webroot/web-inf下简历str.tld文件 <?xml version="1.0" encoding="UTF-8"?> < ...

  2. PAT 1016 部分A+B C语言

    1016. 部分A+B (15) 正整数A的“DA(为1位整数)部分”定义为由A中所有DA组成的新整数PA.例如:给定A = 3862767,DA = 6,则A的“6部分”PA是66,因为A中有2个6 ...

  3. streamsets docker 安装试用

    docker 安装 docker run --restart on-failure -p 18630:18630 -d --name streamsets-dc streamsets/datacoll ...

  4. 【转】foxmail邮箱我已进清理了为什么还是说我的邮箱已满

    原文网址:http://zhidao.baidu.com/link?url=YmX_tBenMVsCopjljd80e2Jwvh7H8GnVSrDLeKKBNQkh_Ty50IsX5eAIy4P_64 ...

  5. GNU Radio: Overview of the GNU Radio Scheduler

    Scetion 1: The Flowgraph The flowgraph moves data from sources into sinks. 一个流图由多个模块组成,其中一般包括信源(Sour ...

  6. erlang的一些系统限制修改

    atom个数限制 +t xxx 进程数限制 +P xxxx ets表个数限制 +e xxx ports个数限制 +Q xxxx 查看限制 string:tokens(binary_to_list(er ...

  7. emacs之配置4,颜色插件

    来自https://github.com/oneKelvinSmith/monokai-emacs/blob/master/monokai-theme.el monokai-theme.el ;;; ...

  8. emacs之配置auto-complete

    el-get-install安装auto-complete emacsConfig/auto-complete-setting.el ;这个是设置一个字母就自动完成的 (setq ac-auto-st ...

  9. EasyUI使用小常识

    datagrid:1 //显示某列 $('#ListTable').datagrid('showColumn', 'ExRate'); //隐藏某列 $('#ListTable').datagrid( ...

  10. 转转转-精通js正则表达式

    原文地址:http://www.cnblogs.com/aaronjs/archive/2012/06/30/2570970.html 正则表达式可以: •测试字符串的某个模式.例如,可以对一个输入字 ...