在项目的开发过程中前后端一般会遇到很多的异常,这些异常的处理后端通常会通过throw出一个对象,前端再将接收到的异常对象code和message进行二次判断或直接将message显示给用户,用户再去操作界面

  1. 首先定义一个返回的异常对象

BusinessException.class

/**
 * @author LiuJunbao
 * @date 2022/5/9 13:27
 */
public class BusinessException extends RuntimeException{
    /**
     * 返回code
     */
    private Integer code;
    /**
     * 返回msg
     */
    private String message;

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

}
  1. 定义一个自定义的异常处理类,方便对各种类型的异常进行抛出。
    tip:ResponseEntity统一返回给前端的实体,属性有code、msg、T data

RestExceptionHandler .class

import lombok.extern.slf4j.Slf4j;
import org.hamburger.common.constant.ResponseCode;
import org.hamburger.common.exception.BusinessException;
import org.hamburger.common.model.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;

/**
 * 自定义异常处理类
 * 针对不同的异常自定义不同的方法
 * 环绕通知
 * 切面:针对所有的controller中抛出的异常
 * 若使用@ControllerAdvice,则不会自动转换为JSON格式
 * @author LiuJunbao
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    /**
     * 业务异常处理
     * @param e
     * @return ErrorInfo
     */
    @ExceptionHandler({BusinessException.class})
    public ResponseEntity<Object> businessExceptionHandler(HttpServletRequest request, BusinessException e)
            throws BusinessException {
        log.error("BusinessException异常:{}", e.getMessage());
        return ResponseEntity.of(ResponseCode.ERROR, e.getMessage(), null);
    }

    /**
     * 业务异常处理
     * @param e
     * @return ErrorInfo
     */
    @ExceptionHandler({AccessDeniedException.class})
    public ResponseEntity<Object> BusinessExceptionHandler(HttpServletRequest request, AccessDeniedException e) throws BusinessException {
        return ResponseEntity.of(401, e.getMessage(), null);
    }

    /**
     * 只要抛出该类型异常,则由此方法处理
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleException(HttpServletRequest request, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        return ResponseEntity.of(ResponseCode.SERVER_INTERNAL_ERROR, e.getMessage(), null);
    }

}

ResponseEntity.class

/**
 * @author LiuJunbao
 * @date 2022/5/9 13:47
 */
public class ResponseEntity<T> {
    /**
     * code
     */
    private Integer code;
    /**
     * msg
     */
    private String msg;
    /**
     * data
     */
    private T data;

    public ResponseEntity() {

    }

    public ResponseEntity(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <A> ResponseEntity<A> of(int code, String msg, A data){
        return new ResponseEntity<>(code, msg, data);
    }
    public static <A> ResponseEntity<A> success(String msg, A data){
        return ResponseEntity.of(ResponseCode.SUCCESS, msg, data);
    }
    public static <A> ResponseEntity<A> error(String desc) {
        return ResponseEntity.of(ResponseCode.ERROR, desc, null);
    }
    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

ResponseCode定义状态码常量

/**
 * @author LiuJunbao
 * @create 2020/12/25 11:36
 */
public interface ResponseCode {
    int SUCCESS = 0;
    /**
     * token没有找到
     */
    int AUTH_TOKEN_NOT_FOUND = 1;
    /**
     * access token失效
     */
    int ACCESS_TOKEN_EXPIRED = 2;
    /**
     * refresh token失效
     */
    int REFRESH_TOKEN_EXPIRED = 3;
    /**
     * 系统内部错误
     */
    int SERVER_INTERNAL_ERROR = 4;
    /**
     * 警告
     */
    int WARNING = 9;
    /**
     * 其它错误
     */
    int ERROR = 99;
}
  1. 在业务处理过程中(一般是Service类中),遇到已知的,需要向客户端展示的业务异常,通过throw一个自己定义的异常对象抛出异常。
public void updatePassword(String userCode,String oldPassword,String newPassword,String newNextPassword){
    Employee employee=employeeRepository.findEmployeeByCode(userCode);
    if(null == employee){
        throw BusinessException.error("用户不存在");
    }
    if(!newPassword.equals(newNextPassword)){
        throw BusinessException.error("两次新密码输入不一致");
    }

}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐