Springboot2.5.x+过滤器异常捕获

之前用的2.2.x版本的,代码有所变化,废话不多说,直接上干货.

package com.mine.common.auth.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.mine.common.core.enums.BaseCode;
import com.mine.common.core.web.domain.AjaxResult;
import com.mine.common.core.web.domain.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>  </p>
 *
 * @author ZY
 * @version 1.0
 * @date 2022/3/18 16:34
 * @since 0.0.1
 */
@Component
public class FilterErrorController extends BasicErrorController {
    public FilterErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    /**
     * Web页面错误处理
     */
    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections
                .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
    }

    /**
     * 除Web页面外的错误处理,比如Json/XML等
     */
    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Object attribute = request.getAttribute("javax.servlet.error.exception");
        String message = "系统异常";
        int busCode = 99999;
        if (attribute instanceof NotLoginException){
            NotLoginException exception = (NotLoginException)attribute;
            message =  exception.getLocalizedMessage();
            busCode = Integer.parseInt(exception.getType());
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        return new ResponseEntity<>(ResponseResult.convertMap(ResponseResult.fail(busCode,message),body), status);
    }
}

其实就是抛出我们想抛出的异常,主要在于这句代码:

Object attribute = request.getAttribute("javax.servlet.error.exception");
Spring Boot中,可以通过统一异常处理机制来捕获和处理逻辑异常。这样的机制可以让我们在发生异常时返回给前端一个友好且易于理解的错误信息,而不是默认的服务器错误页面。 一种常见的实现方法是使用@ControllerAdvice注解,结合@ExceptionHandler注解来定义全局异常处理类。在该类中,我们可以编写方法来处理各种类型的异常,并返回自定义的错误信息。这样,在代码中发生异常时,会自动调用对应的处理方法来处理异常。 你可以参考引用中提供的示例代码来了解更详细的实现方法。在这个示例中,通过使用@ControllerAdvice注解和@ExceptionHandler注解,对不同类型的异常进行了捕获和处理,并返回了自定义的错误信息。 如果你对结果集的详细内容感兴趣,可以参考引用提供的文章链接,里面可能会有更多关于Spring Boot统一异常捕获的相关信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot逻辑异常统一处理方法](https://download.csdn.net/download/weixin_38705004/12745762)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot之全局异常捕获](https://blog.csdn.net/niulinbiao/article/details/120153502)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT界的奇葩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值