1. 继承BasicErrorController

继承BasicErrorController可实现修改默认的全局异常处理,复写error方法修改Rest请求的修改,复写errorHtml实现修改错误处理视图。

package com.nineya.user.controller;

import com.nineya.tool.restful.ResponseResult;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 殇雪话诀别
 * 2020/12/5
 */
@Controller
public class ErrorController extends BasicErrorController {

    public ErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(
                ResponseResult.serverError()
                        .setStatus(status.value())
                        .setMessage(String.valueOf(body.get("message")))
                        .toMap()
                , status);
    }
}

2. ExceptionHandler注解

对于部分异常希望特殊处理的,可使用RestControllerAdvice注解切入Controller,使用ExceptionHandler注解匹配异常,如果匹配成功将会使用该异常处理方法响应,不会采用全局异常处理方法。

package com.nineya.user.handler;

import com.nineya.tool.restful.ResponseResult;
import com.nineya.tool.restful.StatusCode;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author 殇雪话诀别
 * 2020/12/4
 * 异常处理,可在{@link @ErrorController} 之前匹配异常处理,如果在这里匹配到异常处理,controller不会再处理异常信息
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 未知异常的处理方法
     *
     * @param e 异常信息
     * @return 处理结果
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult exceptionHandler(Exception e) {
        return ResponseResult.serverError().setMessage(e.getMessage());
    }

    /**
     * 404错误处理
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseResult notFountHandler() {
        return ResponseResult.failure(StatusCode.NOT_FOUND, "未找到请求内容!");
    }
}

使用该方法需要修改application.yml配置,添加如下内容:

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