SpringBoot项目精简返回给客户端的异常信息

1. 前言

Java Web系统在处理请求时,如果遇到异常,会直接将执行栈的详细信息返回给客户端,这种交互不仅极不友好,而且随意将服务器细节对外展示也是非常危险的。
服务端负责数据访问的DAO层、实现具体业务的Service层以及控制流程的Controller层都可能发生异常,通常我们会在Controller层对异常进行统一处理,当遇到异常时,后端只需返回给前端错误状态码和简单的提示信息,前端再根据精简后的错误信息弹出提示框或者跳转到相应的页面。


2. 思路

后端遵循RESTful规范,控制器类使用@RestController注解,我们只需声明一个Controller增强类并添加上@RestControllerAdvice注解,再使用@ExceptionHandler(value)注解标注异常处理方法即可捕获SpringMVC抛出的异常(value为需要被处理的异常类class,例如填入Exception.class即该方法会捕获所有异常),该类下的方法会自动返回JSON数据给客户端。


3. 代码

import xx.xx.xx.xx.CustomerException
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 精简返回给客户端的异常消息
 * 注解@Slf4j相当于执行了private static final Logger log = LoggerFactory.getLogger(ControllerExceptionAdvice.class)
 * 注解@RestControllerAdvice表示增强Controller功能并返回JSON数据
 */
@Slf4j
@RestControllerAdvice
public class ControllerExceptionAdvice {

    /**
     * 注解@ResponseStatus设置响应状态码
     * 注解@ExceptionHandler设置处理的异常类
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception e) {
        log.error("执行异常", e);
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        } else if (e instanceof CustomerException) {
            CustomerException exception = (CustomerException) e;
            return exception.getMsg();
        } else if (xxxxxx) {
			xxxxxx
			xxxxxx
			......
		} else {
            return "后端执行异常";
        }
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值