后端汇总

注解记录->@ControllerAdvice下的@Except

2019-02-16  本文已影响0人  云鲸鱼rain

之前记录了@AfterThrowing,当切面的类或者方法有异常时,今天看到@ExceptionHandler,对于两者的优先级存在疑问,遂记录。

先记录@ExceptionHandler的作用以及使用场景。
1、如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以在任意地方使用。
2、@ExceptionHandler和@ControllerAdvice能够集中异常,使异常处理与业务逻辑分离。

大概就像下面这样的例子吧

package com.tianci.handle;

import com.tianci.exception.GameException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Create by tianci
 * 2018/9/26 14:42
 */
@ControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String handle(Exception e) {
        if (e instanceof GameException) {
            logger.info("【系统异常】{}", e);
        }
        return "common/error";
    }
}
/**
 * Create by tianci
 * 2019/2/16 9:49
 */

@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "游戏错误")
public class GameException extends RuntimeException {
}

优先级的话,运行程序截图就能说明问题。

结论:AfterThrowing 优先于 ExceptionHandler。

web中常见的通过回调的方式实现的aop有Filter(过滤器)和Interceptor(拦截器)。详情看这位大佬链接即可,每个步骤非常详细。
https://www.cnblogs.com/dugqing/p/8906013.html

上一篇 下一篇

猜你喜欢

热点阅读