美文网首页java专题
最简单springmvc全局异常处理

最简单springmvc全局异常处理

作者: H_Man | 来源:发表于2018-12-10 16:17 被阅读4次

共两种

  • 实现接口
  • 使用注解(简单)

最近做项目在通过异常控制返回值code码,初步思路是定义一个全局异常处理器,上面刚说到有两种方法,先讲第一种.

HandlerExceptionResolver

springmvc给我们提供了可以扩展的接口HandlerExceptionResolver,实现此接口,重写处理异常方法.此方法有些不好用的是在返回值上面.强制我们返回model and view,如果想要返回json,则还需要自己转换一层,下文写到了.

/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;

/**
 * Interface to be implemented by objects that can resolve exceptions thrown during
 * handler mapping or execution, in the typical case to error views. Implementors are
 * typically registered as beans in the application context.
 *
 * <p>Error views are analogous to JSP error pages but can be used with any kind of
 * exception including any checked exception, with potentially fine-grained mappings for
 * specific handlers.
 *
 * @author Juergen Hoeller
 * @since 22.11.2003
 */
public interface HandlerExceptionResolver {

    /**
     * Try to resolve the given exception that got thrown during handler execution,
     * returning a {@link ModelAndView} that represents a specific error page if appropriate.
     * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty}
     * to indicate that the exception has been resolved successfully but that no view
     * should be rendered, for instance by setting a status code.
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the executed handler, or {@code null} if none chosen at the
     * time of the exception (for example, if multipart resolution failed)
     * @param ex the exception that got thrown during handler execution
     * @return a corresponding {@code ModelAndView} to forward to,
     * or {@code null} for default processing in the resolution chain
     */
    @Nullable
    ModelAndView resolveException(
            HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex);

}

如果model and view要转换成普通json返回,则需要手动转换一层:

MappingJackson2JsonView jackson2JsonView = new MappingJackson2JsonView();
    //设置返回的json  map
    Map returnData = Maps.newHashMap();
    //TODO add return data
    jackson2JsonView.setAttributesMap(returnData);
    ModelAndView view = new ModelAndView();
    view.setView(jackson2JsonView);
    return view;
简单方法(使用注解)

在开始说这个之前,我们要先了解一下相关的两个注解

  • @ControllerAdvice,注释大致意思就是 controllerAdvice是一个用于定义@ExceptionHadnler的Component注解.适用于所有的@RequestMapping方法
  • @ExceptionHandler:需要处理的异常,如果不传值默认处理所有异常

使用方法:

import com.immomo.moaservice.live.assess.impl.exception.ActivityAnalyticsException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: hman
 * @date 2018-11-05
 * @desc: 全局异常处理
 */
@RestControllerAdvice
public class ActivityExceptionHandler {

  @ExceptionHandler(ActivityAnalyticsException.class)
  @ResponseBody
  public ResultUtil resolveException(ActivityAnalyticsException e) {
    return ResultUtil.build(e.getCodeEnum());
  }


}


相关文章

  • 最简单springmvc全局异常处理

    共两种 实现接口 使用注解(简单) 最近做项目在通过异常控制返回值code码,初步思路是定义一个全局异常处理器,上...

  • Spring Mvc 异常处理

    SpringMvc 异常全局解读 异常处理思路 首先来看一下在springmvc中,异常处理的思路 如上图所示,系...

  • SpringMVC全局异常处理

    在日常的开发过程中,你肯定遇到过页面报500的问题,这个时候如果我想一想就会觉得害怕,我们的项目如果真的在线上出现...

  • springmvc全局异常处理

    首先定义一个异常类,BusinessException,这个类必须继承RuntimeException类,不然会一...

  • springmvc全局异常处理

    其实用springmvc来实现全局异常处理我在一起的学习demo中也用到了,今天因为有些地方不是那么清晰了,所以干...

  • SpringMvc处理全局异常

    处理全局异常的方法主要为两种: 实现HandlerExceptionResolver接口 @ControllerA...

  • SpringMVC 全局异常处理

    创建ExceptionResolver实现HandlerExceptionResolver接口: 添加@Compo...

  • 全局异常处理

    首先,处理思路,嗯对,就是想想: 其次,创建全局异常处理器,开写 最后,Springmvc中配置异常处理器 ok!...

  • 11.全局异常处理器

    GlobalExceptionResolver.java Springmvc.xml配置全局异常处理器 最终的日志...

  • SpringMVC全局异常

    目录 无SpringMVC全局异常时的流程图 SpringMVC全局异常流程图 配置文件

网友评论

    本文标题:最简单springmvc全局异常处理

    本文链接:https://www.haomeiwen.com/subject/wjfdhqtx.html