控制器异常统一处理方式

    
//捕获当前类中所有的Exception异常
    @ExceptionHandler(Exception.class)
    public @ResponseBody
    Map<String, Object> InterruptedExceptionHandler(InterruptedException interruptedException) {
        logger.error(interruptedException.getMessage());
        Map<String, Object> model = new TreeMap<>();
        model.put("INTERRUPTED_EXCEPTION", interruptedException.getMessage());
        return model;
    }

捕获异常返回页面,添加备注信息提供详

--------------------------------------------------------------------------------------------------------------

异常处理代码

@RestControllerAdvice注解
@ControllerAdvice注解
@ControllerAdvice
public class MyControllerAdvice {
 
    /**
     * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {}
 
    /**
     * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }
 
    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 100);
        map.put("msg", ex.getMessage());
        return map;
    }
 
}





取值----

@RequestMapping("/home")
public String home(ModelMap modelMap) {
    System.out.println(modelMap.get("author"));
}
 
//或者 通过@ModelAttribute获取
 
@RequestMapping("/home")
public String home(@ModelAttribute("author") String author) {
    System.out.println(author);

controller

直接抛出对应异常类

throw new EnforcementServiceException("任务类型错误");

异常类

public class EnforcementServiceException extends RuntimeException {


    public EnforcementServiceException(String message) {
        super(message);
    }


    public EnforcementServiceException(String msg, Throwable cause) {
        super(msg, cause);
    }


    @Override
    public Throwable fillInStackTrace() {
        return this;
    }

    public Throwable doFillInStackTrace() {
        return super.fillInStackTrace();
    }
}

handler 

@ExceptionHandler(EnforcementServiceException.class)
    public ResultData handleError(EnforcementServiceException e, HttpServletResponse response) {
        log.error("业务异常", e);
        if(e.getMessage().equals(String.valueOf(HttpStatus.HTTP_UNAUTHORIZED))) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        }
        return ResultData
                .builder()
                .code(ResultData.SuccessEnum.SUCCESS_200.getCode())
                .status(ResultData.ErrorEnum.ERROR.getCode())
                .message(e.getMessage())
                .success(false)
                .build();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值