170621、springboot编程之全局异常捕获
2017-08-21 13:55
771 查看
1、创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息
2、测试异常信息,在 HelloController.java中制造异常信息
3、效果展示
访问http://localhost:8080/hello,后台抛出异常信息
页面展示效果
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,后台抛出异常信息
页面展示效果
相关文章推荐
- 3-Spring Boot ( 全局捕获异常 与 自定义异常 )
- Spring Boot实战之全局异常捕获 实现参数异常检查返回统一错误信息
- Spring Boot 全局捕获异常
- springboot全局异常捕获
- spring boot 全局异常捕获
- (四)Springboot入门之全局异常捕获
- springboot全局异常捕获
- 一头扎进springboot之捕获全局异常
- SpringBootWEB项目和非Web项目的全局异常捕获
- Spring Boot教程九:捕获全局异常(二)
- SpringBoot系列之三全局异常的捕获处理
- Spring-Boot--日志操作全局异常捕获消息处理☞日志控制台输出+日志文件记录
- 4、springboot之全局异常捕获
- Spring-Boot--日志操作【全局异常捕获消息处理☞日志控制台输出+日志文件记录】
- Spring-Boot--日志操作【全局异常捕获消息处理☞日志控制台输出+日志文件记录】
- Spring Boot教程八:捕获全局异常
- Spring Boot FeignClient 捕获异常信息
- Spring-MVC开发之全局异常捕获全面解读
- SpringBoot全局异常处理