springboot 全局异常处理

@ExceptionHandler  可指定Exception处理。

通过@ResponseBody 可将异常信息以json的方式返回出去

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

 

转载于:https://my.oschina.net/u/2276456/blog/1836242

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值