栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot中使用自定义异常Exception

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot中使用自定义异常Exception

记录一下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("电话号已注册,请您登陆!");
}

捕获异常

try {
    userService.registerStudent(registerVo);
} catch (ServiceException e) {
    return e.getMessage();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/778818.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号