1.创建Exception类   

public class MyException extends RuntimeException {
private ErrorCodeEnum errorCode;

public MyException(ErrorCodeEnum errorCode) {
this.errorCode = errorCode;
}

public ErrorCodeEnum getErrorCode() {
return errorCode;
}

public void setErrorCode(ErrorCodeEnum errorCode) {
this.errorCode = errorCode;
}
}

2.异常枚举类  
public enum ErrorCodeEnum {
INCORRECT_PASSWORD(10001, "密码错误!"),
INUSED_USER(10002, "账号错误!"),
INCORRECT_MSG(10003, "验证码错误!"),

ErrorCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}

private int code;
private String msg;

public int getCode() {
return code;
}

public String getMsg() {
return msg;
}
}




3.全局异常处理类
@ControllerAdvice
public class MyExceptionHandler {
   //捕捉到的异常
@ExceptionHandler(value = MyException.class)
public ResponseEntity<Result> handleServiceException(MyException exception) {
ErrorCodeEnum errorCode = exception.getErrorCode();
return new ResponseEntity(new ResultUtil<String>().setError(errorCode.getCode(), errorCode.getMsg(), ""), HttpStatus.BAD_REQUEST);
}
    //其他异常
@ExceptionHandler
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Result> hadleServerException(Exception exception) {
exception.printStackTrace();
HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
String msg = "server error, please try again later";
Class exceptionClazz = exception.getClass();
if (Objects.equals(MissingServletRequestParameterException.class, exceptionClazz)) {
msg = "incorrect parameter";
httpStatus = HttpStatus.BAD_REQUEST;
} else if (Objects.equals(HttpRequestMethodNotSupportedException.class, exceptionClazz)) {
httpStatus = HttpStatus.BAD_REQUEST;
msg = exception.getMessage();
}
return new ResponseEntity(new ResultUtil<String>().setError(httpStatus.value(), msg, ""), httpStatus);
}
}
posted on   java_zhao  阅读(7870)  评论(0编辑  收藏  举报
编辑推荐:
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
阅读排行:
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 想让你多爱自己一些的开源计时器
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析



点击右上角即可分享
微信分享提示