springmvc统一异常处理拦截器

使用@RestControllerAdvice+@ExceptionHandler实现

也可以使用@ControllerAdvice+@ResponseBody+@ExceptionHandler实现

创建一个异常处理的类,放在config包下

 组件类:

package com.dianping.config;

import com.dianping.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {

    // 捕获运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e) {
        log.error(e.toString(), e);
        return Result.fail("服务器异常");
    }
}

 也可以让不同的异常返回不同的结果,捕获什么异常由@ExceptionHandler的value属性决定,传入一个类对象(可以通过反射获得)

package com.dianping.config;

import com.dianping.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class WebExceptionAdvice {

    // 捕获运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Result handleRuntimeException(RuntimeException e) {
        log.error(e.toString(), e);
        return Result.fail("服务器异常");
    }

    // 捕获空指针异常
    @ExceptionHandler({NullPointerException.class})
    public Result handleNullPointerException(NullPointerException e) {
        return Result.fail("空指针异常");
    }

    // 捕获数字格式异常
    @ExceptionHandler({NumberFormatException.class})
    public Result handleNumberFormatExcption(NumberFormatException e) {
        return Result.fail("数字格式异常");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值