最簡(jiǎn)單springmvc全局異常處理

共兩種

  • 實(shí)現(xiàn)接口
  • 使用注解(簡(jiǎn)單)

最近做項(xiàng)目在通過(guò)異常控制返回值code碼,初步思路是定義一個(gè)全局異常處理器,上面剛說(shuō)到有兩種方法,先講第一種.

HandlerExceptionResolver

springmvc給我們提供了可以擴(kuò)展的接口HandlerExceptionResolver,實(shí)現(xiàn)此接口,重寫(xiě)處理異常方法.此方法有些不好用的是在返回值上面.強(qiáng)制我們返回model and view,如果想要返回json,則還需要自己轉(zhuǎn)換一層,下文寫(xiě)到了.

/*
 * 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要轉(zhuǎn)換成普通json返回,則需要手動(dòng)轉(zhuǎn)換一層:

MappingJackson2JsonView jackson2JsonView = new MappingJackson2JsonView();
    //設(shè)置返回的json  map
    Map returnData = Maps.newHashMap();
    //TODO add return data
    jackson2JsonView.setAttributesMap(returnData);
    ModelAndView view = new ModelAndView();
    view.setView(jackson2JsonView);
    return view;
簡(jiǎn)單方法(使用注解)

在開(kāi)始說(shuō)這個(gè)之前,我們要先了解一下相關(guān)的兩個(gè)注解

  • @ControllerAdvice,注釋大致意思就是 controllerAdvice是一個(gè)用于定義@ExceptionHadnler的Component注解.適用于所有的@RequestMapping方法
  • @ExceptionHandler:需要處理的異常,如果不傳值默認(rèn)處理所有異常

使用方法:

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());
  }


}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容