SpringBoot 异常统一处理

异常统一处理注解

@ControllerAdvice
@ExceptionHandler

为何要统一处理

如果让spring使用默认的处理方式,在生产环境中,如果没有屏蔽错误堆栈信息,可能会暴露系统代码名称以及相应逻辑地址。
image.png

不美观,对于用户来说并不友好。

如何操作

package top.zunmx.nas.middle;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.zunmx.nas.vo.ResponseBodyVO;


@ControllerAdvice
public class ExceptionDeal {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseBodyVO errorHandler(Exception exception) {
        return ResponseBodyVO.failure(exception.getMessage());
    }
}

这样就可以统一管理所有的异常信息了

进阶-处理不同异常

统一处理入口

package top.zunmx.nas.middle;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import top.zunmx.nas.vo.ResponseBodyVO;

import java.util.HashMap;


@ControllerAdvice
public class ExceptionDeal {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseBodyVO errorHandler(Exception exception) {
        return ResponseBodyVO.failure(exception.getMessage());
    }


    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public HashMap errorHandler2(HttpServletRequest req, Exception exception) {
        HashMap<String,String> rst = new HashMap<>();
        rst.put("异常","空指针");
        rst.put("地址",req.getRequestURI());
        return rst;
    }
}

控制层

@GetMapping("/exception")
    public ResponseBodyVO exception() throws Exception {
        throw new Exception("嗡嗡嗡嗡嗡嗡");
    }
@GetMapping("/exception2")
    public String exception2() throws Exception {
        String a ;
        a=null;
        return a.replace("","");
    }

截图

空指针异常

image.png

异常类

image.png

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。