Spring Boot 系列教程6-全局异常处理
@ControllerAdvice源码
package org.springframework.web.bind.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
@AliasFor("basePackages")
String[] value() default {};
@AliasFor("value")
String[] basePackages() default {};
Class<?>[] basePackageClasses() default {};
Class<?>[] assignableTypes() default {};
Class<? extends Annotation>[] annotations() default {};
}
源码说明
@ ControllerAdvice是一个@ Component,
用于定义@ ExceptionHandler的,@InitBinder和@ModelAttribute方法,适用于所有使用@ RequestMapping方法,并处理所有@ RequestMapping标注方法出现异常的统一处理。
项目图片
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jege.spring.boot</groupId>
<artifactId>spring-boot-controller-advice</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-controller-advice</name>
<url>http://maven.apache.org</url>
<!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 持久层 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- h2内存数据库 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<!-- 只在test测试里面运行 -->
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-controller-advice</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
CommonExceptionAdvice.java
package com.jege.spring.boot.exception;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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 com.jege.spring.boot.json.AjaxResult;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:全局异常处理
*/
@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice {
private static Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public AjaxResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
logger.error("缺少请求参数", e);
return new AjaxResult().failure("required_parameter_is_not_present");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public AjaxResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
logger.error("参数解析失败", e);
return new AjaxResult().failure("could_not_read_json");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error("参数验证失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return new AjaxResult().failure(message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public AjaxResult handleBindException(BindException e) {
logger.error("参数绑定失败", e);
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
return new AjaxResult().failure(message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public AjaxResult handleServiceException(ConstraintViolationException e) {
logger.error("参数验证失败", e);
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
return new AjaxResult().failure("parameter:" + message);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public AjaxResult handleValidationException(ValidationException e) {
logger.error("参数验证失败", e);
return new AjaxResult().failure("validation_exception");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public AjaxResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
logger.error("不支持当前请求方法", e);
return new AjaxResult().failure("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public AjaxResult handleHttpMediaTypeNotSupportedException(Exception e) {
logger.error("不支持当前媒体类型", e);
return new AjaxResult().failure("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ServiceException.class)
public AjaxResult handleServiceException(ServiceException e) {
logger.error("业务逻辑异常", e);
return new AjaxResult().failure("业务逻辑异常:" + e.getMessage());
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e) {
logger.error("通用异常", e);
return new AjaxResult().failure("通用异常:" + e.getMessage());
}
/**
* 操作数据库出现异常:名称重复,外键关联
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(DataIntegrityViolationException.class)
public AjaxResult handleException(DataIntegrityViolationException e) {
logger.error("操作数据库出现异常:", e);
return new AjaxResult().failure("操作数据库出现异常:字段重复、有外键关联等");
}
}
ServiceException.java
package com.jege.spring.boot.exception;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:自定义异常类
*/
public class ServiceException extends RuntimeException {
public ServiceException(String msg) {
super(msg);
}
}
Application.java
package com.jege.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:spring boot 启动类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
不需要application.properties
AdviceController
package com.jege.spring.boot.controller;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jege.spring.boot.exception.ServiceException;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:全局异常处理演示入口
*/
@RestController
public class AdviceController {
@RequestMapping("/hello1")
public String hello1() {
int i = 1 / 0;
return "hello";
}
@RequestMapping("/hello2")
public String hello2(Long id) {
String string = null;
string.length();
return "hello";
}
@RequestMapping("/hello3")
public List<String> hello3() {
throw new ServiceException("test");
}
}
访问
- http://localhost:8080/hello1
{“meta”:{“success”:false,”message”:”通用异常:/ by zero”},”data”:null} - http://localhost:8080/hello2
{“meta”:{“success”:false,”message”:”通用异常:null”},”data”:null} - http://localhost:8080/hello3
{“meta”:{“success”:false,”message”:”业务逻辑异常:test”},”data”:null}
源码地址
https://github.com/je-ge/spring-boot
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!
Spring Boot 系列教程6-全局异常处理的更多相关文章
- Spring Boot 系列教程8-EasyUI-edatagrid扩展
edatagrid扩展组件 edatagrid组件是datagrid的扩展组件,增加了统一处理CRUD的功能,可以用在数据比较简单的页面. 使用的时候需要额外引入jquery.edatagrid.js ...
- Spring Boot 系列教程7-EasyUI-datagrid
jQueryEasyUI jQuery EasyUI是一组基于jQuery的UI插件集合体,而jQuery EasyUI的目标就是帮助web开发者更轻松的打造出功能丰富并且美观的UI界面.开发者不需要 ...
- Spring Boot 系列教程19-后台验证-Hibernate Validation
后台验证 开发项目过程中,后台在很多地方需要进行校验操作,比如:前台表单提交,调用系统接口,数据传输等.而现在多数项目都采用MVC分层式设计,每层都需要进行相应地校验. 针对这个问题, JCP 出台一 ...
- Spring Boot 系列教程18-itext导出pdf下载
Java操作pdf框架 iText是一个能够快速产生PDF文件的java类库.iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的.它的类库尤其与java Servlet有很好 ...
- Spring Boot 系列教程17-Cache-缓存
缓存 缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找.由于缓存的运行速度比内存快得多,故缓存的作用就是帮 ...
- Spring Boot 系列教程16-数据国际化
internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ...
- Spring Boot 系列教程15-页面国际化
internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ...
- Spring Boot 系列教程14-动态修改定时任务cron参数
动态修改定时任务cron参数 不需要重启应用就可以动态的改变Cron表达式的值 不能使用@Scheduled(cron = "${jobs.cron}")实现 DynamicSch ...
- Spring Boot 系列教程12-EasyPoi导出Excel下载
Java操作excel框架 Java Excel俗称jxl,可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件,现在基本没有更新了 http://jxl.sourcef ...
随机推荐
- OpenCV2.x自学笔记——Qt5.5.1打包exe
[简易步骤] 1.Release模式下生成exe,在release文件夹内,如jujube.exe 2.exe单独拷贝到一个文件夹,如D:\jujube\jujube.exe 3.打开Qt 官方开发环 ...
- Integer.valueOf(int)及自动装箱内幕
Integer为什么要提供功能与new Integer(xx)一样的valueOf(xx)方法呢,看了源代码之后,我发现了惊人的内幕. public static Integer valueOf(in ...
- amazeui 后台模板
<!doctype html> <html class="no-js"> <head> <meta charset="utf-8 ...
- pc app 桌面打包
进入 http://nwjs.io/ 下载 创建web项目,在项目根目录 创建文件package.json并填写 1 2 3 4 5 6 7 { "name": " ...
- javascript动画效果之透明度(修改版)
在编写多块同时触发运动的时候,发现一个BUG, timer = setInterval(show, 30);本来show是一个自定义函数,当设为timer = setInterval(show(one ...
- C++ 类的继承、虚拟继承、隐藏、占用空间
主函数: #include <iostream> #include "test.h" #include "testfuc.h" using name ...
- iis本地无法通过ip地址访问网站
防火墙等通通检查过没有发现问题,最后发现是我安装了一款adsafe的广告过滤软件捣的鬼,此软件设置界面没有这样的设置条款,估计是默认的配置,退出后,就ok了.
- sql 查询一段时间内某个时间点数据
SELECT CONVERT(VARCHAR(10), dtCreateTime, 120) AS dtStatisticsCreateDate, COUNT(1) AS nStatisticsC ...
- Python 正则表达式学习笔记
本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例.本文的内容不包括如何编写高效的正则表达式.如何优化正则表达式,这些主题请查看其他教程 ...
- VBS基础篇 - 对象(1) - Class对象
VBS基础篇 - 对象(1) - Class对象 相信对JAVA有一定了解的朋友一定对类这个名词不陌生,但是大家可能没有想过在VBS中使用Class类吧,其实Class类在自动化测试中是相当常用的 ...