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

SpringBoot 全局异常处理

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

SpringBoot 全局异常处理

全局异常处理 全局异常处理 自定义异常

创建自定义异常类,并继承Exception或者RunTimeException类,并重写相关方法。

public class UpdateException extends ServiceException{
    public UpdateException() {
        super();
    }

    public UpdateException(String message) {
        super(message);
    }

    public UpdateException(String message, Throwable cause) {
        super(message, cause);
    }

    public UpdateException(Throwable cause) {
        super(cause);
    }

    protected UpdateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}
捕获全局异常
  1. 创建处理全局异常的类
  2. 通过注解**@ControllerAdvice和@ExceptionHandler **标记该类为全局处理异常类和捕获各个不同类型的异常。
@ControllerAdvice
public class BaseController {
	
	
	
    @ResponseBody
    @ExceptionHandler(ServiceException.class)
    public JsonResult ControllerException (Throwable e){
        JsonResult jsonDesign = new JsonResult();
        if (e instanceof UserNameOccupyException){
            jsonDesign.setStatus(3050);
            jsonDesign.setDescription("出现未知错误,数据更新失败!");
        }
        return jsonDesign;
    }

}

手动异常抛出

根据具体的项目实际情况抛出异常,这里就采用主方法演示。

public class Test {

    public static void main(String[] args) {

		//手动抛出异常
        throw new UpdateException("未知错误,数据更新失败!");

    }
}
枚举异常处理

该方式与上一种方法相比较,使用枚举异常处理的方式可以减少类的创建。

创建枚举类
public enum ExceptionEnum {

    UpdateException(3050,"遇到未知错误,数据更新失败!");

	//响应代码
    private int code;
	//响应的消息
    private String message;

    ExceptionEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}
创建自定义异常

创建自定义异常,继承RunTimeException。

public class GlobalException extends RuntimeException{
	
    private ExceptionEnum exceptionEnum;

    public GlobalException(ExceptionEnum exceptionEnum) {
        this.exceptionEnum = exceptionEnum;
    }

    public ExceptionEnum getExceptionEnum() {
        return exceptionEnum;
    }

}
捕获全局异常
@ControllerAdvice
public class GlobalExceptionController {

    @ExceptionHandler(GlobalException.class)
    public JsonResult ControllerException(GlobalException e){
        JsonResult jsonDesign = new JsonResult();
        
        //code
        jsonDesign.setStatus(e.getExceptionEnum().getCode());
        //详细消息
        jsonDesign.setDescription(e.getExceptionEnum().getMessage());
        return jsonDesign;
    }
}
手动抛出异常
throw new GlobalException(ExceptionEnum.UpdateException);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/999637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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