@ExceptionHandler

功能描述

当控制器方法抛出指定类型的异常时,被 @ExceptionHandler 注解标注的方法会被调用,用于处理异常情况,例如返回特定的错误响应、记录错误日志等

代码示例

针对项目最全局异常处理,返回指定格式

import fri.bhlz.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
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.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
 
import java.io.PrintWriter;
import java.io.StringWriter;
 
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @Value("${spring.servlet.multipart.max-file-size}")
    private String MAX_SIZE;
 
    /**
     * 全局异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        String msg = "系统异常";
        if (e instanceof MaxUploadSizeExceededException) {
            msg = "文件上传大小限制为:" + MAX_SIZE;
        }
        if (e instanceof BindException) {
            msg = ((BindException) e).getBindingResult().getFieldError().getDefaultMessage();
        }
        e.printStackTrace();
        log.error("系统捕获异常");
        log.error(e.getMessage());
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        log.error(sw.toString());
 
        return new Result(-1, msg, null);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值