假如我们需要针对NullException(空指针异常,是Java程序员最痛恨的异常,没有之一)进行全局处理(如下所示)。
方案一:
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理空指针的异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =NullPointerException.class)
public BaseResponseFacade exceptionHandler(HttpServletRequest req, NullPointerException e){
log.error("发生空指针异常!原因是:",e);
return ResponseUtil.error(ResponseCode.ERROR);
}
}
或者自定义异常
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@Accessors(chain = true)
public class BizException extends RuntimeException {
/**
* 错误码
*/
protected Integer errorCode;
/**
* 错误信息
*/
protected String errorMsg;
}
显而易见,这个异常继承了RuntimeException,属于运行时异常,抱错能够会滚;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理自定义的业务异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = BizException.class)
public BaseResponseFacade bizExceptionHandler(HttpServletRequest req, BizException e){
log.error("发生业务异常!原因是:{}",e.getErrorMsg());
return ResponseUtil.error(e.getErrorCode(),e.getErrorMsg());
}
/**
* 处理空指针的异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =NullPointerException.class)
public BaseResponseFacade exceptionHandler(HttpServletRequest req, NullPointerException e){
log.error("发生空指针异常!原因是:",e);
return ResponseUtil.error(ResponseCode.ERROR);
}
测试请求
@GetMapping("/test")
public BaseResponseFacade test(){
if(true){
throw new BizException(1,"error");
}
return ResponseUtil.success();
}
结果
地址栏请求,进入这个方法后,会抛出异常,此时全局异常生效,就会返回异常处理过后的信息
{“errorCode”:1,“errorMsg”:“error”,“data”:null}
方案二:
2.1定义1级继承类
//定义业务异常
public class TransException extend RuntimeExcepton{
private static final lang serialVersionUID = 1L;
private String rtnCode;
private String rtnDesc;
//get\set方法
public TransException(String rntCode,String rtnMsg){
super(rtnMsg);
this.rtnCode = rtnCode;
this.rtnDesc = rtnMsg;
}
}
y也可以定义二级异常类
public class TransSpecialException extend TransException {
public TransSpecialException (String rntCode,String rtnMsg){
super(rntCode,rtnMsg);
}
}
2.2交易内部抛出,公共基类进行捕捉
throw new transException(“1234”,“1234”);