springboot 全局異常處理

@ExceptionHandler  可指定Exception處理。java

經過@ResponseBody 可將異常信息以json的方式返回出去web

package com.antong.api.handler;

import javax.servlet.http.HttpServletRequest;

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.servlet.ModelAndView;

import com.antong.common.constant.Constants;
import com.antong.common.exception.AuthException;
import com.antong.common.util.Ret;

/**   
* Copyright: Copyright (c) 2018 zq_tuo
* 
* @ClassName: GlobalExceptionHandler.java
* @Description: 統一異常處理
* @version: v1.0.0
* @author: tuozq
* @date: 2018年6月26日 下午1:33:25 
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2018年6月26日     tuozq           v1.0.0               修改緣由
*/

@ControllerAdvice
public class GlobalExceptionHandler {
	
	public static final String DEFAULT_ERROR_VIEW = "error";
	
	/*
    跳轉至自定義異常界面 
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }*/

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Ret defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        return Ret.fail(Constants.MESSAGE, e.getMessage()).set("uri", req.getRequestURI());
    }
    
    /**
     * 針對特定異常 特殊處理
     * @param req  request請求
     * @param e 異常對象
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = AuthException.class)
    @ResponseBody
    public Ret AuthExceptionHandler(HttpServletRequest req, AuthException e) throws Exception {
        return Ret.fail(Constants.MESSAGE, e.getMessage()).set(Constants.CODE, e.getCode());
    }
	
}
相關文章
相關標籤/搜索