首页 > 其他分享 >springboot的全局异常处理类

springboot的全局异常处理类

时间:2022-09-23 11:33:46浏览次数:58  
标签:JsonResult springboot error springframework org import 全局 异常 defaultMessage

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(code = HttpStatus.METHOD_NOT_ALLOWED)
    public JsonResult handleException(HttpRequestMethodNotSupportedException e) {
        logger.error(e.getMessage(), e);
        return JsonResult.error("不支持' " + e.getMethod() + "'请求");
    }

    @ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e) throws Exception {
        logger.error(e.getMessage(), e);
        return JsonResult.error("服务器错误,请联系管理员");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleValidException(MethodArgumentNotValidException e){
        //日志记录错误信息
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("=================校验器触发错误================" + defaultMessage);
        //将错误信息返回给前台
        return JsonResult.error(defaultMessage);
    }

    @ExceptionHandler(BusinessException.class)
    public JsonResult handleValidException(BusinessException e){
        //日志记录错误信息
        String defaultMessage = e.getMessage();
        log.error("=================校验器触发错误================" + defaultMessage);
        //将错误信息返回给前台
        return JsonResult.error(defaultMessage);
    }
}

标签:JsonResult,springboot,error,springframework,org,import,全局,异常,defaultMessage
From: https://www.cnblogs.com/srjx/p/16722083.html

相关文章