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. SSH整合时多表关联查询出现Javassist增强失败

    Customer类对应的表为另一个表LinkMan的外键,在进行LinkMan表操作时,出现如下错误. 遇到Javassist增强失败网上说法不一,有的说Customer没有无参构造方法,javass ...

  2. Python练习:小程序,列车出票程序

    # 需求:列车某结车厢座位有15行,5列,初始状态均为'有票',当乘客选了座次,下单后,变更为'已售' # 下单时,要显示所有座位的状态(有票or已售) # 下单完毕后,显示下单后的座位状态. lin ...

  3. ApacheTomcat 8 9 安全配置与高并发优化

    编辑修改配置文件 [root@DaMoWang ~]# vim /usr/local/tomcat/conf/server.xml 禁用8005端口 telnet localhost 8005 然后输 ...

  4. 通过js或jq增加的代码,点击事件或其他一些事件不起作用时

    通过js或jq增加的代码,点击事件或其他一些事件不起作用时,可使用 $(document).on("click",".noshow",function() { ...

  5. Oracle 体系结构chapter2

    前言:Oracle 体系结构其实就是指oracle 服务器的体系结构,数据库服务器主要由三个部分组成 管理数据库的各种软件工具(sqlplus,OEM等),实例(一组oracle 后台进程以及服务器中 ...

  6. cookie,localStorage和sessionStorage的区别

    cookie已经很久没有用过了,一直觉得session Storage和local Storage更加好用一些.

  7. Mysql 聚合函数返回NULL

    [1]聚合函数返回NULL 当where条件不满足时,聚合函数sum().avg()的返回值为NULL. (1)源数据表 (2)如下SQL语句 SELECT sClass, COUNT(*) AS t ...

  8. SQL Server嵌套事务

    一.@@TRANCOUNT 在将事务前,我们先来了解一下@@TRANCOUNT ,@@trancount返回上传执行begin transaction语句的事务计数. 1.每执行一次begin tra ...

  9. Springboot 实现多环境配置

    多环境配置 我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发.测试.生产等.其中每个环境的数据库地址.服务器端口等等配置都会不同,如果在为不同环境打包时 ...

  10. Genymotion-Android模拟器提示"Unable to connect to the Genymotion server. Please check your Internet connection."解决方法

    昨天刚装的Genymotion,昨晚还用得好好的. 今晚开机,重新打开Genymotion,却提示:"Unable to connect to the Genymotion server. ...