SpringBoot自定义异常 返回code、message给前端(@RestControllerAdvice)

在项目的开发过程中前后端一般会遇到很多的异常,这些异常的处理后端通常会通过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("两次新密码输入不一致");
    }

}
  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
SpringBoot中,我们可以通过自定义异常来处理业务逻辑中出现的异常情况。以下是实现步骤: 1. 自定义异常类 在项目包中创建一个自定义的异常类,需要继承Exception或RuntimeException。 ``` public class CustomException extends RuntimeException { private int code; private String message; public CustomException(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } ``` 2. 异常处理类 在项目包中创建一个异常处理类,需要使用@ControllerAdvice和@ExceptionHandler注解,通过指定异常类来捕获异常并处理。 ``` @ControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(CustomException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result handleCustomException(CustomException e) { return new Result(e.getCode(), e.getMessage(), null); } } ``` 3. 统一响应对象 在项目包中创建一个统一响应对象类,用于统一封装响应信息。 ``` public class Result<T> { private int code; private String message; private T data; public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } } ``` 以上就是springboot自定义异常的实现步骤。在业务逻辑中抛出自定义异常即可触发异常处理类中的处理方法,并返回统一响应对象。这样可以统一处理异常并返回规范化的响应信息,方便前端或其他系统的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值