使用ControllerAdvice统一异常处理

话祥 / 2024-02-28 / 原文

使用注解@ControllerAdvice统一处理系统的异常。

package com.springweb.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
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 javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class GlobalException {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public String globalException(NullPointerException exception, HttpServletRequest request){
        log.error("happen NullPointerException url:{}, exception message:", request.getRequestURI(), exception);
        return "系统异常,请联系管理员!";
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String globalException(Exception exception, HttpServletRequest request){
        log.error("happen exception url:{}, exception message:", request.getRequestURI(), exception);
        return "系统异常,请联系管理员!";
    }

}