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

springmvc请求参数异常统一处理的更多相关文章

  1. springmvc请求参数异常统一处理,结合钉钉报告信息定位bug位置

    参考之前一篇博客:springmvc请求参数异常统一处理 1.ExceptionHandlerController package com.oy.controller; import java.tex ...

  2. SpringMVC请求参数接收总结

    前提 在日常使用SpringMVC进行开发的时候,有可能遇到前端各种类型的请求参数,这里做一次相对全面的总结.SpringMVC中处理控制器参数的接口是HandlerMethodArgumentRes ...

  3. SpringMVC请求参数接收总结(一)

    前提 在日常使用SpringMVC进行开发的时候,有可能遇到前端各种类型的请求参数,这里做一次相对全面的总结.SpringMVC中处理控制器参数的接口是HandlerMethodArgumentRes ...

  4. SpringMVC请求参数总结

    前提 在日常使用SpringMVC进行开发的时候,有可能遇到前端各种类型的请求参数,这里做一次相对全面的总结.SpringMVC中处理控制器参数的接口是HandlerMethodArgumentRes ...

  5. 2.5万字长文简单总结SpringMVC请求参数接收

    这是公众号<Throwable文摘>发布的第22篇原创文章,暂时收录于专辑<架构与实战>.暂定下一篇发布的长文是<图文分析JUC同步器框架>,下一篇发布的短文是&l ...

  6. springmvc请求参数异常处理

    接着上一篇<springmvc 通过异常增强返回给客户端统一格式>讲通过spring ControllerAdvice对各种异常进行拦截处理,统一格式返回给客户端. 接下来我们更精细的讲, ...

  7. springmvc 请求参数解析细节

    springmvc 的请求流程,相信大家已经很熟悉了,不熟悉的同学可以参考下资料! 有了整体流程的概念,是否对其中的实现细节就很清楚呢?我觉得不一定,比如:单是参数解析这块,就是个大学问呢? 首先,我 ...

  8. SpringMVC请求参数注解两个小问题

    今天遇到使用SpringMVC请求注解遇到的两个小问题: 如果用@requestBody注解,则请求体内容类型一般要为application/json,如果其类型为multipart/form-dat ...

  9. SpringMVC请求参数和响应结果全局加密和解密

    前提 前段时间在做一个对外的网关项目,涉及到加密和解密模块,这里详细分析解决方案和适用的场景.为了模拟真实的交互场景,先定制一下整个交互流程.第三方传输(包括请求和响应)数据报文包括三个部分: 1.t ...

随机推荐

  1. PHP7的异常处理机制,set_error_handler和set_exception_handler方法介绍

    https://blog.csdn.net/zhang197093/article/details/75094816

  2. Django框架详细介绍---请求流程

    Django请求流程图 1.客户端发送请求 2.wsgiref是Django封装的套接字,它将客户端发送过来的请求(请求头.请求体封装成request) 1)解析请求数据 2)封装响应数据 3.中间件 ...

  3. 记录心得-IntelliJ iDea 创建一个maven管理的的javaweb项目

    熟能生巧,还是记录一下吧~ 开始! 第一步:File--New--Project--Maven--Create from archetype--maven-archetype-webapp 第二步:解 ...

  4. MyBatis探究-----配置数据源的几种方式

    1.在核心配置文件mybatis-config.xml中配置数据库连接信息 mysql的j驱动jar包是mysql-connector-java-6.0.6.jar mysql版本5.7 <?x ...

  5. Log4j介绍与使用

    Log4j三大组件 1) 日志记录器Logger负责输出日志信息,并能够对日志信息进行分类筛选,决定哪些日志信息应该被输出,哪些该被忽略.Loggers组件输出日志信息时分为5个级别:DEBUG.IN ...

  6. 2018-2019-2 网络对抗技术 20165305 Exp2 后门原理与实践

    常用后门工具 一.Windows获得Linux Shell 在Windows下使用ipconfig查看本机IP 使用ncat.exe程序监听本机的5305端口 在Kali环境下,使用nc指令的-e选项 ...

  7. Linux基础命令---tload显示系统负载

    tload tload指令以字符的方式显示当前系统的平均负载情况. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.SUSE.openSUSE.   1.语法   ...

  8. left join on +多条件与where区别

    left join on +多条件与where区别 重点 先匹配,再筛选where条件. 本文将通过几个例子说明两者的差别. 1. 单个条件 select * from product a left ...

  9. php,js 对字符串按位异或运算加密解密

    异或的符号是^.按位异或运算, 对等长二进制模式按位或二进制数的每一位执行逻辑按位异或操作. 操作的结果是如果某位不同则该位为1, 否则该位为0. xor运算的逆运算是它本身,也就是说两次异或同一个数 ...

  10. element-ui 2.4.3 如何实现对form部分字段验证的解决方法?

    这是实际项目中的一个例子: 新增人员信息功能: 必填:姓名 .电话(验证电话格式): 非必填:备注.微信.邮箱(验证邮箱格式) 必填验证: 邮箱格式验证: 今天偶然看到 element-ui 2.4. ...