Spring Boot2.x:统一异常处理
1. 实现思路:
- 需要配合@ExceptionHandler使用。
- 当将异常抛到controller时,可以对异常进行统一处理,规定返回的json格式或是跳转到一个错误页面
2. 首先创建全局异常捕捉处理类:GlobleExceptionHandler.java
package com.ieslab.powergrid.demosvr.utils;
import com.ieslab.powergrid.demosvr.entity.MyException;
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 java.util.HashMap;
import java.util.Map;
/** <p>Title: GlobleExceptionHandler </p>
* <p>Description: 全局异常捕捉处理</p>
*
* @author houpeibin
* @date 2020-2-20 下午7:15:30
* @version V1.0
*/
@ControllerAdvice
public class GlobleExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception ex) {
Map map = new HashMap();
map.put("code", 400);
//判断异常的类型,返回不一样的返回值
if(ex instanceof MissingServletRequestParameterException){
map.put("msg","缺少必需参数:"+((MissingServletRequestParameterException) ex).getParameterName());
}
else if(ex instanceof MyException){
map.put("msg","这是自定义异常");
}
return map;
}
}
3.创建自定义异常类:MyException.java
package com.ieslab.powergrid.demosvr.entity;
import lombok.Data;
import org.springframework.web.bind.annotation.RestController;
//自定义异常类
@Data
public class MyException extends RuntimeException {
private long code;
private String msg;
public MyException(Long code, String msg){
super(msg);
this.code = code;
this.msg = msg;
}
public MyException(String msg){
super(msg);
this.msg = msg;
}
}
4.创建TestController.java
package com.ieslab.powergrid.demosvr.controller;
import com.ieslab.powergrid.demosvr.entity.MyException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** <p>Title: TestController </p>
* <p>Description: 测试全局异常捕获功能</p>
*
* @author houpeibin
* @date 2020-2-20 下午7:15:30
* @version V1.0
*/
@RestController
public class TestController {
@RequestMapping("testException")
public String testException() throws Exception{
throw new MissingServletRequestParameterException("name","String");
}
@RequestMapping("testMyException")
public String testMyException() throws MyException {
throw new MyException("i am a myException");
}
}
这个controller类型中,定义了两个方法,都是直接抛出异常,看看是否能够被统一异常类捕获,请运行程序后访问:http://localhost:8080/testException
访问:http://localhost:8080/testMyException
5.总结
统一异常处理集成完毕,是不是很简单???