//这是全局拦截异常拦截器
package com.springboot.admin.exception;
import com.springboot.admin.Result;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler {
/**
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
* @param binder
*/
@InitBinder
public void initWebBinder(WebDataBinder binder){
}
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* @param model
*/
@ModelAttribute
public void addAttribute(Model model) {
model.addAttribute("attribute", "The Attribute");
}
/**
* 捕获MyException
* @param e
* @return json格式类型
*/
@ResponseBody
@ExceptionHandler({MyException.class}) //指定拦截异常的类型
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //自定义浏览器返回状态码
public Result myExceptionHandler(MyException e) {
return Result.error(e.getCode(), e.getMessage());
}
/**
* 捕获Exception
* @param e
* @return json格式类型
*/
@ResponseBody
@ExceptionHandler({Exception.class}) //指定拦截异常的类型
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //自定义浏览器返回状态码
public Result allExceptionHandler(Exception e) {
return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.toString());
}
}
//这是我的自定义异常
package com.springboot.admin.exception;
public class MyException extends RuntimeException {
private String message;
private int code;
public MyException(int code, String message) {
super(message);
this.message = message;
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
//测试
public Result testException() throws Exception {
Ups ups = upsMapper.selectById(1);
ups.setUid(2);
ups.setTypeId(8);
upsMapper.updateById(ups);
Ups ups1 = upsMapper.selectById(1);
System.out.println("type_id----------------" + ups1.getTypeId());
// int a = 1 / 0;
throw new MyException(1, "打印错误信息");
}
注意: 抛出异常时必须抛出 RuntimeException 才能捕捉到,另外,自定义异常也必须继承 RuntimeException 异常,否则也是无法捕捉的。RuntimeException 才能回滚
注意:尽量只拦截自定义异常,如果全部拦截,不方便查看所有报错信息。