前言
本文讲解使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,可以处理大部分开发中用到的自自定义业务异常处理了,再也不用在 Controller 层进行 try-catch 了
一、处理思路
- 思路:在sevice业务逻辑层 try{}catch(){} 捕获抛出,经由contorller 层抛到 自定义全局处理类 中处理自定义异常及系统异常。
2、实现方式:使用 @RestControllerAdvice + @ExceptionHandler 注解方式实现全局异常处
二、实现过程
1、@RestControllerAdvice 注解定义全局异常处理类 ,@ExceptionHandler 注解声明异常处理方法。
package com.exception;
import com.response.DefaultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author wanjiadong
* @description
* @date Create in 11:17 2019/1/5
*/
@RestControllerAdvice
@Slf4j
public class UniteExceptionHandler {
@ExceptionHandler({Exception.class})//拦截指定异常
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//指定游览器返回状态码
public DefaultResponse uniteExceptionHandler(Exception e) {
log.error("uniteExceptionHandler");
return new DefaultResponse();
}
@ExceptionHandler(BusinessException.class)
public DefaultResponse businessExceptionHandler(BusinessException e) {
log.error("businessExceptionHandler:"+e.getMessage());
return new DefaultResponse();
}
}
package com.exception;
/**
* @author wanjiadong
* @description
* @date Create in 13:52 2019/1/5
*/
public class BusinessException extends RuntimeException {
private Integer code;
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}