zoukankan      html  css  js  c++  java
  • 170621、springboot编程之全局异常捕获

    1、创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息

    
    
    package com.rick.common.handler;

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.util.IOUtils;
    import com.rick.common.ResultJson;
    import com.rick.common.exception.BusinessException;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.PrintWriter;

    @ControllerAdvice
    public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    System.out.println("=====================全局异常信息捕获=======================");

    String msg;
    if(ex instanceof BusinessException){
    msg = ex.getMessage();
    } else {
    msg = "操作异常!";
    }
    ex.printStackTrace();
    PrintWriter out = null;
    try {
    out = response.getWriter();
    out.print(JSON.toJSON(ResultJson.buildFailInstance(msg)).toString());
    } catch(Exception e){
    e.printStackTrace();
    } finally {
    IOUtils.close(out);
    }

    return null;
    }
    }

    2、测试异常信息,在 HelloController.java中制造异常信息

    @RestController
    public class HelloController {
    
        @RequestMapping("/hello")
        public String hello(){
            System.out.println(1/0);//制造异常信息
            return "Hello World!";
        }
    }

    3、效果展示

    访问http://localhost:8080/hello,后台抛出异常信息

    页面展示效果

  • 相关阅读:
    网络学习笔记
    zabbix4.2学习笔记系列
    ansible2.7学习笔记系列
    记一次磁盘UUID不能识别故障处理
    白话ansible-runner--1.环境搭建
    kubernetes的思考
    计算机网络原理精讲第六章--应用层
    计算机网络原理精讲第五章--传输层
    centos7下LVM挂载和扩容
    多线程下载命令--axel
  • 原文地址:https://www.cnblogs.com/zrbfree/p/7404018.html
Copyright © 2011-2022 走看看