处理方式一:
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.全局异常处理类
package com.baizhi.exceptions;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@ControllerAdvice
public class MyExceptionHandler {
//捕捉到的异常
@ExceptionHandler(value =MyException.class)
public Map<String,String> getException(MyException e){
Map<String, String> map = new HashMap<>();
map.put("msg",e.getErrorCode().getMsg());
return map;
}
}
处理方式二:
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
/**
* 错误信息实体类
*/
public class ErrorMessage implements Serializable {
private Integer errorCode;
private String message;
}
两个自定义异常类
package com.baizhi.exceptions;
public class UsernameAndPasswordException extends RuntimeException{
public UsernameAndPasswordException(String message){
super(message);
}
}
package com.baizhi.exceptions;
public class VerifyCodeException extends RuntimeException {
public VerifyCodeException(String message) {
super(message);
}
}
package com.baizhi.controller;
import com.baizhi.entities.ErrorMessage;
import com.baizhi.exceptions.UsernameAndPasswordException;
import com.baizhi.exceptions.VerifyCodeException;
import org.springframework.web.bind.annotation.*;
/**
* 全局异常处理
*/
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(value = UsernameAndPasswordException.class)
public ErrorMessage errorhandler(UsernameAndPasswordException e){
return new ErrorMessage(001,e.getMessage());
}
@ResponseBody
@ExceptionHandler(value = VerifyCodeException.class)
public ErrorMessage errorhandler(VerifyCodeException e){
return new ErrorMessage(002,e.getMessage());
}
}