最简单springmvc全局异常处理

共两种

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

最近做项目在通过异常控制返回值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());
  }


}


    原文作者:H_Man
    原文地址: https://www.jianshu.com/p/7a62d10c3db3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞