008 Spring Boot 自定义异常处理输出

访问 Spring Boot server 时,当内部出现异常的话,Spring Boot 有一套自己的异常处理,同时向页面输出相关内容。

比如,当我们访问一个不存在的路由时,Spring Boot 默认会返回:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Oct 14 16:51:35 CST 2022
There was an unexpected error (type=Not Found, status=404).

Whitelabel Error Page

出于各种考量,当 server 出现异常时,我们希望是输出我们自定义的内容,此时我们只需要创建我们自己的异常处理。

1. 新建类

package org.example.controller;

import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class DefExceptionHandle {
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public String exceptionHandler(HttpServletRequest req, RuntimeException e) {
        return "运行时异常: " + e.getMessage();
    }

    /**
     * 处理空指针的异常
     *
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public String exceptionHandler(HttpServletRequest req, NullPointerException e) {
        return "处理空指针的异常: " + e.getMessage();
    }

    /**
     * 处理请求方法不支持的异常
     *
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public String exceptionHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e) {
        return "理请求方法不支持的异常: " + e.getMessage();
    }

    /**
     * 处理其他异常
     *
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String exceptionHandler(HttpServletRequest req, Exception e) {
        return "处理其他异常: " + e.getMessage();
    }

    @ExceptionHandler(value = ArithmeticException.class)
    @ResponseBody
    public String exceptionHandler(HttpServletRequest req, ArithmeticException e) {
        return "运算异常: " + e.getMessage();
    }
}

2. 修改配置文件

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

操作以上两部分,就可以自定义异常的输出了。

源码:

发表评论