• 使用@ControllerAdvice及@ExceptionHandler(value = Exception.class)全局异常处理


    http://snowolf.iteye.com/blog/1636050

    Spring 注解学习手札(八)补遗——@ExceptionHandler

    http://412887952-qq-com.iteye.com/blog/2291524

    全局异常捕捉【从零开始学Spring Boot】


    package com.ilex.jiutou;
    
    import com.ilex.jiutou.vo.PageResult;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * Created by sunyuming on 17/5/11.
     */
    @ControllerAdvice
    public class GlobalDefaultExceptionHandler {
    
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public PageResult defaultErrorHandler(HttpServletRequest req, Exception e)  {
    //      // If the exception is annotated with @ResponseStatus rethrow it and let
    //      // the framework handle it - like the OrderNotFoundException example
    //      // at the start of this post.
    //      // AnnotationUtils is a Spring Framework utility class.
    //      if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
    //          throw e;
    //
    //      // Otherwise setup and send the user to a default error-view.
    //      ModelAndView mav = new ModelAndView();
    //      mav.addObject("exception", e);
    //      mav.addObject("url", req.getRequestURL());
    //      mav.setViewName(DEFAULT_ERROR_VIEW);
    //      return mav;
    
                //打印异常信息:
                e.printStackTrace();
                System.out.println("GlobalDefaultExceptionHandler.defaultErrorHandler()");
    
           /*
            * 返回json数据或者String数据:
            * 那么需要在方法上加上注解:@ResponseBody
            * 添加return即可。
            */
    
           /*
            * 返回视图:
            * 定义一个ModelAndView即可,
            * 然后return;
            * 定义视图文件(比如:error.html,error.ftl,error.jsp);
            *
            */
           return PageResult.genFail("服务器繁忙");
        }
    
    }


    这种方式,异常仍然由spring捕获,与http://blog.csdn.net/silyvin/article/details/54645168相比,事务中无需显式回滚

    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

  • 相关阅读:
    日记 2018/1/12
    【程序员笔试面试必会——排序①】Python实现 冒泡排序、选择排序、插入排序、归并排序、快速排序、堆排序、希尔排序
    Python笔试、面试 【必看】
    高性能Go并发
    Go连接MySql数据库Error 1040: Too many connections错误解决
    MAC 配置文件 ~/.zshrc
    go-statsd项目
    日记 2017.11.20
    sed 命令详解
    Opentsdb简介(一)
  • 原文地址:https://www.cnblogs.com/silyvin/p/9106800.html
Copyright © 2020-2023  润新知