All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.youm.frame.webmvc.handler.GlobalExceptionHandler Maven / Gradle / Ivy

There is a newer version: 1.2.5
Show newest version
package me.youm.frame.webmvc.handler;

import cn.dev33.satoken.exception.NotLoginException;
import io.sentry.Sentry;
import lombok.extern.slf4j.Slf4j;
import me.youm.frame.common.exception.AuthorityException;
import me.youm.frame.common.exception.BusinessException;
import me.youm.frame.common.exception.IdempotentException;
import me.youm.frame.common.exception.TokenException;
import me.youm.frame.common.model.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.nio.file.AccessDeniedException;

/**
 * @author youta
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {


    /**
     * BusinessException 异常捕获处理
     *
     * @param ex 自定义BusinessException异常类型
     * @return Result
     */
    @ExceptionHandler(BusinessException.class)
    public Result handleException(HttpServletRequest request, BusinessException ex) {
        Result result = Result.error(ex.getCode(),ex.getMessage());
        this.getRequestURI(request);
        log.error(result.toString(), ex);
        Sentry.captureException(ex);
        return result;
    }


    /**
     * TokenException 异常捕获处理
     *
     * @param ex 自定义TokenException异常类型
     * @return Result
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result handleException(HttpServletRequest request, TokenException ex) {
        Result result = Result.error(HttpStatus.UNAUTHORIZED.value(),ex.getMessage());
        this.getRequestURI(request);
//        log.error(result.toString(), ex);
//        Sentry.captureException(ex);
        return result;
    }


    /**
     * AuthorityException 异常捕获处理
     *
     * @param ex 自定义AuthorityException异常类型
     * @return Result
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result handleException(HttpServletRequest request, AuthorityException ex) {
        Result result = Result.error(HttpStatus.FORBIDDEN.value(),ex.getMessage());
        this.getRequestURI(request);
        log.error(result.toString(), ex);
//        Sentry.captureException(ex);
        return result;
    }


    @ExceptionHandler
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result handleException(HttpServletRequest request, NotLoginException ex) {
        Result result = Result.error(HttpStatus.UNAUTHORIZED.value(),ex.getMessage());
        this.getRequestURI(request);
//        log.error(result.toString(), ex);
//        Sentry.captureException(ex);
        return result;
    }


    @ExceptionHandler
    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
    public Result handleException(HttpServletRequest request, IdempotentException ex) {
        Result result = Result.error(HttpStatus.TOO_MANY_REQUESTS.value(),ex.getMessage());
        this.getRequestURI(request);
        log.error(result.toString(), ex);
        Sentry.captureException(ex);
        return result;
    }

    /**
     * FileNotFoundException,NoHandlerFoundException 异常捕获处理
     *
     * @param exception 自定义FileNotFoundException异常类型
     * @return Result
     */
    @ExceptionHandler({FileNotFoundException.class, NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result noFoundException(HttpServletRequest request,Exception exception) {
        Result result = Result.error(HttpStatus.NOT_FOUND.value(),exception.getMessage());
        this.getRequestURI(request);
        log.error(result.toString(), exception);
        Sentry.captureException(exception);
        return result;

    }


    /**
     * 不支持请求方法异常处理
     *
     * @param e 异常对象
     * @see ExceptionHandler
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result methodNotSupportHandler(HttpServletRequest request,HttpRequestMethodNotSupportedException e) {
        Result result = Result.error(HttpServletResponse.SC_METHOD_NOT_ALLOWED,"不支持当前请求方法");
        this.getRequestURI(request);
        log.error(result.toString(), e);
        Sentry.captureException(e);
        return result;

    }

    /**
     * 不支持当前媒体类型异常处理
     *
     * @param ex 异常对象
     * @see ExceptionHandler
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public Result mediaTypeNotSupportHandler(HttpServletRequest request,HttpMediaTypeNotSupportedException ex) {
        Result result = Result.error(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,"不支持当前媒体类型");
        this.getRequestURI(request);
        log.error(result.toString(), ex);
        Sentry.captureException(ex);
        return result;

    }

    /**
     * 不支持当前媒体类型异常处理
     *
     * @param ex 异常对象
     * @see ExceptionHandler
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result messageNotReadableHandler(HttpServletRequest request,HttpMessageNotReadableException ex) {
        Result result = Result.error(HttpServletResponse.SC_BAD_REQUEST,"消息不能读取");
        this.getRequestURI(request);
        log.error(result.toString(), ex);
        Sentry.captureException(ex);
        return result;

    }

    /**
     * NullPointerException 空指针异常捕获处理
     *
     * @param ex 自定义NullPointerException异常类型
     * @return Result
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(HttpServletRequest request,NullPointerException ex) {
        Result result = Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),ex.getMessage());
        this.getRequestURI(request);
        log.error(result.toString(), ex);
        Sentry.captureException(ex);
        return result;

    }

    /**
     * NullPointerException 空指针异常捕获处理
     *
     * @param ex 自定义NullPointerException异常类型
     * @return Result
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result handleException(HttpServletRequest request, AccessDeniedException ex) {
        Result result = Result.error(HttpStatus.FORBIDDEN.value(),ex.getMessage());
        this.getRequestURI(request);
        log.error(result.toString(), ex);
//        Sentry.captureException(ex);
        return result;

    }


    /**
     * 通用Exception异常捕获
     *
     * @param ex 自定义Exception异常类型
     * @return Result
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(HttpServletRequest request,Exception ex) {
        Result result = Result.error();
        this.getRequestURI(request);
        log.error(result.toString(), ex);
        Sentry.captureException(ex);
        return result;
    }


    /**
     * 参数校验异常
     *
     * @param e 异常对象
     * @return Result   返回类型
     * @throws
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result errorBindHandler(BindException e) {
        log.error("BindException -> param check error", e);
        Sentry.captureException(e);
        return wrapperBindingResult(e.getBindingResult());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        this.getRequestURI(request);
        log.error("MethodArgumentNotValidException -> param bind check error", e);
        Sentry.captureException(e);
        return wrapperBindingResult(e.getBindingResult());
    }


    /**
     * IllegalArgumentException(非法参数)异常处理返回json 状态码:400
     *
     * @param exception 异常对象
     * @return Result
     */
    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result badRequestException(HttpServletRequest request, IllegalArgumentException exception) {
        this.getRequestURI(request);
        log.error("IllegalArgumentException -> 400", exception);
        Sentry.captureException(exception);
        return Result.error(exception.getMessage());
    }

    /**
     * 获取请求URI
     *
     * @param request
     */
    private void getRequestURI(HttpServletRequest request) {
        // 获取请求路径
        String requestUrl = request.getRequestURI();
        log.error("request URI [{}] fail", requestUrl);
    }


    /**
     * 包装绑定异常结果
     *
     * @param bindingResult 绑定结果
     * @return R 异常结果
     */
    private Result wrapperBindingResult(BindingResult bindingResult) {
        // 构建返回消息
        StringBuilder msg = new StringBuilder();
        for (ObjectError error : bindingResult.getAllErrors()) {
            msg.append(", ");
            if (error instanceof FieldError) {
                msg.append(((FieldError) error).getField()).append(": ");
            }
            msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
        }
        return Result.error(msg.substring(2));
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy