spring boot 全局异常处理

import cn.sisyphe.framework.web.exception.DataException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ming
 * @desc 全局异常处理类
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 缺失请求参数处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public ResponseResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String message = "缺失请求参数" + e.getParameterName();
        return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
    }

    /**
     * 请求参数类型错误处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public ResponseResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String message = "请求参数" + e.getName() + "类型错误";
        return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
    }

    /**
     * 参数类型错误异常类型处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    @ResponseBody
    public ResponseResult handleHttpMessageNotReadableException(HttpMessageConversionException e, HttpServletRequest request) {
        String message = "参数类型错误";
        return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
    }

    /**
     * 空指针异常处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public ResponseResult handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        String message = "空指针异常";
        return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e, true);
    }

    /**
     * MethodArgumentNotValidException 异常处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        StringBuilder errorMsg = new StringBuilder();
        BindingResult re = e.getBindingResult();
        for (ObjectError error : re.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return ackTransfer(request, errorMsg.toString(), "-1", e, false);
    }

    /**
     * 绑定异常处理
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseResult handleBindException(BindException e,HttpServletRequest request){
        BindingResult result = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return ackTransfer(request, errorMsg.toString(), "-1", e, false);
    }

    /**
     * 自定义异常类型异常消息处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({DataException.class})
    @ResponseBody
    public ResponseResult handleDataException(DataException e, HttpServletRequest request) {
        String message = e.getErrorMessage();
        String code = e.getErrorCode();
        return ackTransfer(request, code, message, e, true);
    }

    /**
     * 处理运行时异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public ResponseResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        return ackTransfer(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value() + "", e, true);
    }

    /**
     * 默认异常处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult handleException(Exception e, HttpServletRequest request) {
        return ackTransfer(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value() + "", e, true);
    }

    private ResponseResult ackTransfer(HttpServletRequest request, String message, String code, Exception e, boolean printStackTrace) {
        ResponseResult result = new ResponseResult();
        result.setCode(code);
        result.setMessage(message);
        if (printStackTrace) {
            log.error(message, e);
        } else {
            log.error(message);
        }
        return result;
    }

    private ResponseResult ackTransfer(HttpServletRequest request, String message, String code, Exception e) {
        return ackTransfer(request, message, code, e, false);
    }
}

原文地址:https://www.cnblogs.com/huzi007/p/11684194.html

时间: 2024-10-29 01:18:18

spring boot 全局异常处理的相关文章

Spring Boot 全局异常配置

Spring Boot 全局异常配置,处理异常控制器需要和发生异常的方法在一个类中.使用 ControllerAdvice 注解 package com.li.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import

Spring Boot全局支持CORS(跨源请求)

1 import org.springframework.context.annotation.Configuration; 2 import org.springframework.web.servlet.config.annotation.CorsRegistry; 3 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 4 5 /** 6 * @Author:CoderZZ 7

Spring boot全局捕获异常处理!

package com.htli.util; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.Re

Spring boot集中异常处理

集中异常处理 方式一:ExceptionHandle 定义自己的异常类型,根据不同类型做不同处理,比如我定义的MyException: public class MyException extends RuntimeException { public MyException(String msg) { super(msg); } } 然后通过MyExceptionHandle处理该异常,需要注意的是异常不能在filter中抛出,抛出也没法捕获 @RestControllerAdvice pub

spring boot 全局配置属性一览

# =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application.               ^^^ # =====================

Spring MVC全局异常处理与拦截器校检

在使用Spring MVC进行开发时,总是要对系统异常和用户的异常行为进行处理,以提供给用户友好的提示,也可以提高系统的安全性. 拦截系统响应错误 首先是拦截系统响应错误,这个可以在web.xml中配置,根据错误代码跳转到相应的提示页面.这里要注意一个问题,错误处理页面所用到的静态资源最好是直接写在页面中,或者同一个文件夹下,因为如果用户访问了一个系统不存在的路径,例如:**/ss/kk/ll/tt.jsp这样就会有404错误就会跳转到相应的处理页面,但是这个处理页面中的静态资源的路径就会变成*

Spring MVC全局异常处理

继承HandlerExceptionResolver接口实现自己的处理方法,如: public class MyHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception

Spring Boot? 统一异常处理

效果区:  代码区: package com.wls.integrateplugs.exception.dto; public class ErrorInfo<T> { public static final Integer OK = 200; public static final Integer ERROR = 500; private Integer code; private String message; private String url; private T data; pub

Spring boot 全局配置 properties或者yml文件报错

主要问题是没有扫描到配置文件 在pom文件里面<build>    </build>中加上以下代码就可以保证能扫描到了 <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.yml</include> <include>**/*.properties</include