前后端分离 SSM 统一异常处理 解决404不被拦截的问题

优点就不再啰嗦了...................

感谢@书呆子Rico,

这位博主在spring-mvc.xml文件中设置了

<!--使用默认的Servlet来响应静态文件-->
<mvc:default-servlet-handler/>
导致spring对404的错误码不能拦截。


代码撸起来吧..........................

统一返回文件

Response.java

package com.yatai.mypro.utils;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.security.interfaces.RSAPrivateCrtKey;

/**
 * Created by gaozhenbo on 17-12-24.
 */
public class Response {

    private static final String OK = "ok";
    private static final String ERROR = "error";
    // 成功状态
    public static final Integer SUCCESS_CODE = 200;
    // ERROR
    public static final Integer ERROR_CODE = 202;

    private Meta meta;//元数据
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Object data;//相应内容

    public Response success() {
        this.meta = new Meta(true, OK);
        this.meta.code = SUCCESS_CODE;
        return this;
    }

    public Response success(Object data) {
        this.meta = new Meta(true, OK);
        this.meta.code = SUCCESS_CODE;
        this.data = data;
        return this;
    }

    public Response failure() {
        this.meta = new Meta(false, ERROR);
        this.meta.code = ERROR_CODE;
        return this;
    }

    public Response failure(String message) {
        this.meta = new Meta(false, message);
        this.meta.code = ERROR_CODE;
        return this;
    }

    public Meta getMeta() {
        return meta;
    }

    public Object getData() {
        return data;
    }

    public class Meta {

        private boolean success;
        private String message;
        private Integer code;

        public Meta(boolean success) {
            this.success = success;
        }

        public Meta(boolean success, String message) {
            this.success = success;
            this.message = message;
        }

        public boolean isSuccess() {
            return success;
        }

        public String getMessage()

        {
            return message;
        }

        public Integer getCode() {
            return code;
        }

    }

}


全局异常文件GlobalExceptionAspect.java

package com.yatai.mypro.utils.exception;

import com.yatai.mypro.utils.Response;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Created by gaozhenbo on 17-12-24.
 * 利用 @ControllerAdvice + @ExceptionHandler 组合处理Controller层RuntimeException异常
 */

@ControllerAdvice
@ResponseBody
public class GlobalExceptionAspect  {

    private static final Logger log = Logger.getLogger(GlobalExceptionAspect.class);

    /*
    *  400-Bad Request
    */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response handleHttpMessageNotReadableException(
            HttpMessageNotReadableException e) {
        log.error("无法读取JSON...", e);
        return new Response().failure("无法读取JSON");
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleValidationException(MethodArgumentNotValidException e)
    {
        log.error("参数验证异常...", e);
        return new Response().failure("参数验证异常");
    }

    /**
     * 404-NOT_FOUND
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Response handlerNotFoundException(NoHandlerFoundException e)
    {
        log.error("请求的资源不可用",e);
        return new Response().failure("请求的资源不可用");
    }

    /*
    * 405 - method Not allowed
    * HttpRequestMethodNotSupportedException 是ServletException 的子类,需要Servlet API 支持
    *
    */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        log.error("不合法的请求方法...",e);
        return new Response().failure("不合法的请求方法");
    }

    /**
     * 415-Unsupported Media Type.HttpMediaTypeNotSupportedException是ServletException的子类,需要Serlet API支持
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({ HttpMediaTypeNotSupportedException.class })
    public Response handleHttpMediaTypeNotSupportedException(Exception e) {
        log.error("内容类型不支持...", e);
        return new Response().failure("内容类型不支持");
    }

   /* *//**
     * 500 - Internal Server Error
     *//*
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(TokenException.class)
    public Response handleTokenException(Exception e) {
        log.error("令牌无效...", e);
        return new Response().failure("令牌无效");
    }*/

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        log.error("内部服务错误...", e);
        return new Response().failure("内部服务错误");
    }

}
controller文件

package com.yatai.mypro.controller;

import com.yatai.mypro.utils.Response;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController  {

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public Response test()
    {
        Response response = new Response();
        return response.failure("123");
    }
}

有web.xml配置文件的SSM架构实现如下:

<servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <param-name>throwExceptionIfNoHandlerFound</param-name>
            <param-value>true</param-value>
        </init-param>

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>

因为 DispatcherServlet源码中对于 throwExceptionIfNoHandlerFound 默认是 false 我们需要在初始化DispatcherServlet时将参数值更改为true.


spring-mvc.xml

 <!-- 扫描controller(controller层注入) -->
    <context:component-scan base-package="com.yatai.mypro.controller,com.yatai.mypro.utils.exception" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>
我用的是maven多模块SSM所以 base-package放在了不同的文件夹下,可以用逗号来追加扫描目录好让spring能够看到统一异常这个类

<!--支持Controller的AOP代理-->
    <aop:aspectj-autoproxy/>
    <!-- 会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,
		这是SpringMVC为@Controllers分发请求所必需的,并提供了数据绑定支持、@NumberFormatannotation支持、 @DateTimeFormat支持、@Valid支持、读写XML的支持和读写JSON的支持等功能。 -->
    <!-- 启动注解支持 -->

    <mvc:annotation-driven />
    <!--使用默认的Servlet来响应静态文件-->
    <!--<mvc:default-servlet-handler/>-->
这个地方有一个坑就是如果我们 使用默认的Servlet来响应静态文件 那么web.xml设置的throwExceptionIfNoHandlerFound 就会失效,
所以一定要注释调此处
 

相关链接

http://blog.csdn.net/justloveyou_/article/details/74379479

http://rensanning.iteye.com/blog/2355214

https://stackoverflow.com/questions/36000137/how-to-handle-404-page-not-found-exception-in-spring-mvc-with-java-configuration

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值