1、ExceptionHandlerController

package com.oy.controller;

import java.text.MessageFormat;

import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
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 org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; import com.alibaba.fastjson.JSONObject; import com.oy.exception.ForbiddenException;
import com.oy.utils.UtilFunctions; @ControllerAdvice
public class ExceptionHandlerController { @ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public JSONObject runtimeExceptionHandler(RuntimeException ex) {
UtilFunctions.log.error("runtimeExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
response.put("message", "Internal Server Error");
return response;
} @ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public JSONObject nullPointerExceptionHandler(NullPointerException ex) {
UtilFunctions.log.error("nullPointerExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
response.put("message", "Internal Server Error");
return response;
} /*----- REQUEST ERROR -----*/
@ExceptionHandler({ ForbiddenException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public JSONObject requestForbidden(ForbiddenException ex) {
UtilFunctions.log.error("ForbiddenExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
response.put("message", ex.getMessage());
return response;
} @ExceptionHandler({ TypeMismatchException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public JSONObject requestTypeMismatch(TypeMismatchException ex) {
UtilFunctions.log.error("TypeMismatchExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
// response.put("message", "Bad Request");
// response.put("message", "Bad Request, parameter type of " + ex.getPropertyName() + " need be " + ex.getRequiredType()); if (Double.class.equals(ex.getRequiredType()) || Integer.class.equals(ex.getRequiredType())) {
response.put("message", "Bad Request, " + ex.getValue() + " not a number");
} else {
String strTemplate = "Bad Request, {0} is invalid, a type of {1} is needed";
response.put("message", MessageFormat.format(strTemplate, ex.getValue(), ex.getRequiredType().getName()));
}
return response;
} @ExceptionHandler({ MissingServletRequestParameterException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public JSONObject requestMissingServletRequest(MissingServletRequestParameterException ex) {
UtilFunctions.log.error("MissingServletRequestParameterExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
// response.put("message", "Bad Request");
String strTemplate = "Bad Request, param:{0} is required, type:{1}";
response.put("message", MessageFormat.format(strTemplate, ex.getParameterName(), ex.getParameterType()));
return response;
} @ExceptionHandler({ NoSuchRequestHandlingMethodException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public JSONObject NoSuchRequestHandlingMethodExceptionHandler(NoSuchRequestHandlingMethodException ex) {
UtilFunctions.log.error("NoSuchRequestHandlingMethodExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
response.put("message", "Not Found");
return response;
} /*----- REQUEST ERROR -----*/
@ExceptionHandler({ HttpMessageNotReadableException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public JSONObject requestNotReadable(HttpMessageNotReadableException ex) {
UtilFunctions.log.error("HttpMessageNotReadableExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
response.put("message", "Bad Request");
return response;
} @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ResponseBody
public JSONObject request405(HttpRequestMethodNotSupportedException ex) {
UtilFunctions.log.error("HttpRequestMethodNotSupportedExceptionHandler, msg:{}, exception:{}", ex.toString(), ex);
JSONObject response = new JSONObject();
// response.put("message", "Method Not Allowed");
response.put("message", ex.getMessage());
return response;
}
}

2、postman测试

3、异常增强类型:

  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)

参考资料:

  (1)springmvc通过异常增强返回给客户端统一格式

  (2)springmvc请求参数异常处理

  (3)@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

  (4)https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html

最新文章

  1. sublime自动生成头部注释
  2. Git远程操作详解
  3. 年轻的团队Mono玩转Dalvik
  4. HDU 1573 X问题 (中国剩余定理)
  5. Jsp(3):内置对象和四种域对象的理解
  6. whu oj 1551 Pairs (莫队算法)
  7. .Net程序调试与追踪的一些方法
  8. 【BZOJ3143】游走(高斯消元,数学期望)
  9. 安卓测试工具uiautomator无法打开失败报错解决方案
  10. topcoder srm 693 div1 -3
  11. 42-2017蓝桥杯b java
  12. python flask 项目结构
  13. JS-点和中括号
  14. C语言 · 图形输出
  15. Web服务器实现文件传输程序设计
  16. 取url中的参数值
  17. 【分类讨论】Codeforces Round #395 (Div. 2) D. Timofey and rectangles
  18. 【discuz】G变量注解之 $_G['member'] 全局当前登录者信息
  19. SQLServer与ASP中DATEDIFF函数区别
  20. java深入探究15-SpringMVC

热门文章

  1. 利用Openssh后门 劫持root密码
  2. 简单尝试Spring Cloud Gateway
  3. Java获取项目根目录等其他系统属性
  4. Angular4 构建,部署,多环境
  5. 浅谈USB驱动架构 转载
  6. Linux CAN Shell 测试脚本程序
  7. Python数据分析Pandas库之熊猫(10分钟二)
  8. Java RSA 公钥加密私钥解密
  9. 火狐开发----从头用到尾的cfx
  10. js字母/字符与ASCII码转换