我们在实际项目开发中,在不同的硬件或者软件环境下会出现很多异常情况,如果每个地方都要去捕获各种异常,那么程序会很臃肿,如果服务端错误的信息直接暴露给用户,那样的体验会很糟糕,这些信息甚至被黑客用来攻击我们的服务,导致更大的事故,所以我们今天弄一个全局异常处理。
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.5.2version>
<relativePath/>
parent>
<groupId>com.aliangroupId>
<artifactId>exceptionartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>exceptionname>
<description>Spring Boot之全局异常description>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<version>${parent.version}version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
先定义一个异常信息类,包括错误码和异常信息。
ErrorResponseEntity.java
package com.alian.exception.exceptions;
import java.io.Serializable;
public class ErrorResponseEntity implements Serializable {
private static final long serialVersionUID = -4383509268106883368L;
private int errorCode;
private String errorMessage;
public ErrorResponseEntity() {
super();
}
public ErrorResponseEntity(int errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
要实现自定义的异常,我编写的类可以继承RuntimeException,相当于我们的类也是一个运行时异常类。
CustomException.java
package com.alian.exception.exceptions;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = -8793729160842629256L;
private int errorCode;
public CustomException() {
super();
}
public CustomException(int errorCode, String message) {
super(message);
this.setErrorCode(errorCode);
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
在spring 3.2中,新增了@ControllerAdvice,@RestControllerAdvice注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中,从源码中我们也知道@RestControllerAdvice就是@ControllerAdvice和@ResponseBody的合并,此注解通过对异常的拦截实现的统一异常返回处理,返回json格式的异常。
GlobalExceptionHandler.java
package com.alian.exception.exceptions;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 全局异常处理
*/
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
/**
* 捕获 RuntimeException 异常
* RuntimeException下面有很多的子类,你也可以分多个exceptionHandler去处理不同的异常
*/
@ExceptionHandler(RuntimeException.class)
public ErrorResponseEntity runtimeExceptionHandler(HttpServletRequest request, final Exception ex, HttpServletResponse response) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
RuntimeException exception = (RuntimeException) ex;
return new ErrorResponseEntity(400, exception.getMessage());
}
/**
* 捕获我们自定义的异常,可以多个 @ExceptionHandler({xxx.class})
*/
@ExceptionHandler(CustomException.class)
public ErrorResponseEntity customExceptionHandler(HttpServletRequest request, final Exception ex, HttpServletResponse response) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
CustomException exception = (CustomException) ex;
return new ErrorResponseEntity(exception.getErrorCode(), exception.getMessage());
}
/**
* 接口映射异常处理方,主要是请求接口时的一些异常,如果想提示明显一点,就自己转一下if(ex instanceof xxxException)
*/
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (ex instanceof HttpRequestMethodNotSupportedException) {
HttpRequestMethodNotSupportedException exception = (HttpRequestMethodNotSupportedException) ex;
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "不支持[" + exception.getMethod() + "]的请求方式"), status);
}
if (ex instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
}
if (ex instanceof MethodArgumentTypeMismatchException) {
MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
System.out.println("参数转换失败,方法:" + exception.getParameter().getMethod().getName() + ",参数:" + exception.getName()
+ ",信息:" + exception.getLocalizedMessage());
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "参数转换失败"), status);
}
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), ex.getMessage()), status);
}
}
当系统抛出CustomException异常时会被我们自定义异常处理捕获,完成异常信息返回。handleExceptionInternal这个接口映射异常处理方法,主要是请求接口时的一些异常,如果你有特定的异常需要提示的,可以自定义处理,比如我这里提示不支持get方法。
application.properties
server.port=8088
server.servlet.context-path= /exception
ExceptionController.java
package com.alian.exception.controller;
import com.alian.exception.exceptions.CustomException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* 全局异常演示
*/
@RequestMapping("/test")
@RestController
public class ExceptionController {
/**
* 演示类型转换及RuntimeException(除数为0)
*
* @param num1
* @param num2
* @return
*/
@RequestMapping("/division/{num1}/{num2}")
public String division(@PathVariable Integer num1, @PathVariable Integer num2) {
int result = num1 / num2;
return "计算的结果:" + result;
}
/**
* 演示输入数据异常
* @param request
* @return
*/
@RequestMapping("/input")
public String input(HttpServletRequest request) {
String data = request.getParameter("data");
if (data == null || "".equals(data) || "null".equals(data)) {
throw new CustomException(1000, "输入数据不能为空");
}
return "输入的数据为:" + data;
}
/**
* 演示不支持的请求方式*(此处是只支持post)
*/
@PostMapping("/unSupportGet")
public String unSupportGet() {
return "我是post请求方法";
}
}
按照我们的demo随便写了几个请求返回,异常都被我们捕获到了,见下方表格:
请求地址 | 返回结果 |
---|---|
http://localhost:8088/exception/test/division/100/30 | 计算的结果:10 |
http://localhost:8088/exception/test/division/100/0 | {“errorCode”:400,“errorMessage”:"/ by zero"} |
http://localhost:8088/exception/test/input?data=10086 | 输入的数据为:10086 |
http://localhost:8088/exception/test/input?data= | {“errorCode”:1000,“errorMessage”:“输入数据不能为空”} |
http://localhost:8088/exception/test/unSupportGet | {“errorCode”:405,“errorMessage”:“不支持[GET]的请求方式”} |