SpringBoot中使用自定义异常Exception

2023-05-16

记录一下SpringBoot中使用自定义异常操作方法,代码如下;
创建ServiceException.class

public class ServiceException extends RuntimeException{
    private int code = 500;

    public ServiceException() { }
    public ServiceException(String message) {
        super(message);
    }
    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }
    public ServiceException(Throwable cause) {
        super(cause);
    }
    public ServiceException(String message, Throwable cause,
                            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
    public ServiceException(int code) {
        this.code = code;
    }
    public ServiceException(String message, int code) {
        super(message);
        this.code = code;
    }
    public ServiceException(String message, Throwable cause,
                            int code) {
        super(message, cause);
        this.code = code;
    }
    public ServiceException(Throwable cause, int code) {
        super(cause);
        this.code = code;
    }
    public ServiceException(String message, Throwable cause,
                            boolean enableSuppression, boolean writableStackTrace, int code) {
        super(message, cause, enableSuppression, writableStackTrace);
        this.code = code;
    }
    public int getCode() {
        return code;
    }
}

创建ExceptionControllerAdvice.class


import com.lyxl.common.project.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//ExceptionControllerAdvice
//这个类是专门处理控制器发生的异常的
//@RestControllerAdvice表示当前类是处理控制器通知功能的
@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {

    //编写处理异常的方法
    //每个方法可以处理一种异常,可以编写多个方法
    //@ExceptionHandler表示下面方式专门处理异常
    // 如果控制器中发生的异常类型和这个方法的参数匹配,就运行这个方法
    @ExceptionHandler //Handler(处理者)
    public String handlerServiceException(ServiceException e){
        log.error("业务异常",e);
        return e.getMessage();
    }
    //一个类可以有多个处理异常的方法,每个方法处理不同的异常类型
    // 这里处理异常的父类Exception,表示出现任何异常,当前类都处理
    @ExceptionHandler
    public String handlerException(Exception e){
        log.error("其它异常",e);
        return e.getMessage();
    }



}

在业务中使用

if (users.size() > 1) {
	throw new ServiceException("用户数量大于1!");
}
if (null!=user.getPhone) {
            throw new Exception("电话号已注册,请您登陆!");
}

捕获异常


userService.registerStudent(registerVo);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot中使用自定义异常Exception 的相关文章

随机推荐