枚举封装SpringBoot全局异常处理

来自Guide哥的文章

本文使用 @ControllerAdvice 和 @ExceptionHandler 处理全局异常。

利用枚举封装全局异常。有两个点:如何封装全局异常,如何利用封装的全局异常。

第一步如何封装全局异常。

在这里插入图片描述

package com.hmdp.config;

import org.springframework.http.HttpStatus;

/**
 * @Classname ErrorCode
 * @Description
 * @Date 2023/10/28 17:00
 * @Created by cc
 */
public enum ErrorEnum {
    //这个类的主要作用就是统一管理系统中可能出现的异常,比较清晰明了。
    // 但是,可能出现的问题是当系统过于复杂,出现的异常过多之后,这个类会比较庞大。
    // 有一种解决办法:将多种相似的异常统一为一个,
    //          比如将用户找不到异常和订单信息未找到的异常都统一为“未找到该资源”这一种异常,
    //          然后前端再对相应的情况做详细处理(我个人的一种处理方法,不敢保证是比较好的一种做法)。


 


    ERROR(false,"错误")
    ,ERROR_NOTFOUND(false,"没有找到资源");
    
    
    private final Boolean success;
    private final String errorMsg;

    ErrorEnum(Boolean success, String errorMsg) {
        this.success = success;
        this.errorMsg = errorMsg;
    }

    public Boolean getSuccess() {
        return success;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    @Override
    public String toString() {
        return "ErrorEnum{" +
                "success=" + success +
                ", errorMsg='" + errorMsg + '\'' +
                '}';
    }

    
}

第二步 如何利用被封装的全局异常

首先 先自定义一个异常,但是先别首先,因为要自定义很多个异常一般来说,所以我们先定义一个基础的异常,让其他的异常去继承它。
然后就可以在全局异常中处理异常了。

1.基础异常

在这里插入图片描述

package com.hmdp.config;

import org.springframework.util.ObjectUtils;



/**
 * @Classname BaseException
 * @Description
 * @Date 2023/10/28 17:06
 * @Created by cc
 */
public class BaseException extends  RuntimeException{

    private  final ErrorEnum error;
    private    Object data ;
    private     long total;

    public BaseException(ErrorEnum error, Object data,int total){
        super(error.getErrorMsg());
        this.error=error;
        if (!ObjectUtils.isEmpty(data)) {
            this.data=data;
        }else data=null;
        this.total=0;
    }

    public BaseException(ErrorEnum error, Object data,int total,Throwable throwable){
        super(error.getErrorMsg());
        this.error=error;
        if (!ObjectUtils.isEmpty(data)) {
            this.data=data;
        }else data=null;
        total=0;
    }

    public ErrorEnum getError() {
        return error;
    }

    public Object getData() {
        return data;
    }

    public long getTotal() {
        return total;
    }

 }

2.自定义异常
package com.hmdp.config;

/**
 * @Classname NotFoudException
 * @Description
 * @Date 2023/10/28 20:50
 * @Created by cc
 */
public class NotFoudException extends BaseException{
    public NotFoudException(ErrorEnum error, Object data, int total) {
        super(ErrorEnum.ERROR_NOTFOUND, data, total);
    }
}

4.全局异常中处理异常

在这里插入图片描述

package com.hmdp.config;

import com.hmdp.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;



@Slf4j
@RestControllerAdvice(assignableTypes = Exception.class)
public class WebExceptionAdvice {

    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e) {
        log.error(e.toString(), e);
        return Result.fail("服务器异常");
    }

    @ExceptionHandler(value = BaseException.class)
    public Result handle(BaseException ex){
        return    Result.fail(ex);
    }
    @ExceptionHandler(value = NotFoudException.class)
    public Result handle(NotFoudException ex){
        return    Result.fail(ex);
    }



}

响应类

package com.hmdp.dto;

import com.hmdp.config.BaseException;
import com.hmdp.config.ErrorEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private Boolean success;
    private String errorMsg;
    private Object data;
    private Long total;

    public static Result ok(){
        return new Result(true, null, null, null);
    }
    public static Result ok(Object data){
        return new Result(true, null, data, null);
    }
    public static Result ok(List<?> data, Long total){
        return new Result(true, null, data, total);
    }
    public static Result fail(String errorMsg){
        return new Result(false, errorMsg, null, null);
    }
    public static Result fail(BaseException ex){
        return new Result(ex.getError().getSuccess(), ex.getError().getErrorMsg(), ex.getData(), ex.getTotal());
    }
}

总结一下

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值