main
commit
963b9e1ec5
@ -0,0 +1,41 @@
|
||||
package org.example.exception;
|
||||
|
||||
import org.example.common.CommonResp;
|
||||
|
||||
public class CustomException extends RuntimeException implements CommonResp {
|
||||
|
||||
private final CommonResp commonResp;
|
||||
|
||||
public CustomException(CommonResp commonResp) {
|
||||
super(); // 调用父类的无参构造方法
|
||||
this.commonResp = commonResp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return this.commonResp.getMsg();
|
||||
}
|
||||
|
||||
// 接收自定义msg的方式构造业务异常
|
||||
public CustomException(String msg, CommonResp commonResp) {
|
||||
super();
|
||||
this.commonResp = commonResp;
|
||||
this.commonResp.setMsg(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCode() {
|
||||
return this.commonResp.getCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMsg() {
|
||||
return this.commonResp.getMsg();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CommonResp setMsg(String msg) {
|
||||
this.commonResp.setMsg(msg);
|
||||
return this;
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package org.example.exception;
|
||||
|
||||
import cn.hutool.log.Log;
|
||||
import cn.hutool.log.LogFactory;
|
||||
import cn.hutool.log.level.Level;
|
||||
import org.example.common.ResponseStatusEnum;
|
||||
import org.example.utils.Result;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
|
||||
@RestControllerAdvice // 返回json
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
private static final Log log = LogFactory.get();
|
||||
|
||||
|
||||
// 统一异常处理@ExceptionHandler,主要用于Exception 运行时异常
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public Result handler(RuntimeException e) {
|
||||
log.error("运行时异常:", e);
|
||||
return Result.error("-1", "后台运行异常,请联系系统管理员!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 其他异常
|
||||
* @param e 异常
|
||||
* @return 提示
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result handler(Exception e) {
|
||||
log.error("系统异常:", e);
|
||||
return Result.error("-1", "系统异常,请联系系统管理员!");
|
||||
}
|
||||
|
||||
//统一异常处理@ExceptionHandler,主要用于Exception 自定义异常
|
||||
@ExceptionHandler(value = CustomException.class)
|
||||
public Result handler(CustomException e) {
|
||||
log.error("发生业务异常!原因是:{}", e.getMsg());
|
||||
return Result.error(e.getCode(), e.getMsg());
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = HttpMessageNotReadableException.class)
|
||||
public Result handler(HttpMessageNotReadableException exception) {
|
||||
log.log(Level.ERROR, exception.getMessage());
|
||||
return Result.error(ResponseStatusEnum.REQUEST_BODY_MISSING);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in new issue