Spring boot全局异常处理405,415,500

字数 45阅读 5017

首先把SpringBoot默认的异常处理屏蔽掉:

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false
server:
  error:
    whitelabel:
      enabled: false

如下代码, 其中401,403处理是配合shiro使用的, 当没有授权时,shiro指定 /error/403跳转

package com.ztdz.tmss.web.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;

/**
 * <b>标题:    </b><br />
 * <pre>
 * </pre>
 *
 * @author 毛宇鹏
 * @date 创建于 上午11:23 2018/1/9
 */
@ControllerAdvice
@RestController
@RequestMapping( value = "/error")
public class ControllerException extends BaseController  {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public String httpRequestMethodNotSupportedException(HttpServletResponse response) {
        response.setStatus(200);
        return RESPONSE_INTERFACE.errorJSONString(405, "method 方法不支持");
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public String httpMediaTypeNotSupportedException(HttpServletResponse response) {
        response.setStatus(200);
        return RESPONSE_INTERFACE.errorJSONString(415, "不支持媒体类型");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFoundPage404(HttpServletResponse response) {
        response.setStatus(200);
        return RESPONSE_INTERFACE.errorJSONString(404,"没有找到访问资源");
    }

    @RequestMapping(value = "/401" ,produces = {"application/json;charset=UTF-8"})
    public String forbidden401(HttpServletResponse response) {
        response.setStatus(200);
        System.out.println("401");
        return RESPONSE_INTERFACE.errorJSONString(401,"没有访问权限");
    }

    @RequestMapping(value = "/403" ,produces = {"application/json;charset=UTF-8"})
    public String forbidden403(HttpServletResponse response) {
        response.setStatus(200);
        System.out.println("403");
        return RESPONSE_INTERFACE.errorJSONString(403,"没有访问权限");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String defaultException(HttpServletResponse response) {
        response.setStatus(200);
        return RESPONSE_INTERFACE.errorJSONString(500, "网络异常");
    }
}

推荐阅读更多精彩内容