springboot学习笔记之简单异常处理
springboot学习笔记之简单异常处理
全局级别异常处理器 @ControllerAdvice+@ExceptionHandler
package com.demo.utils;
import java.util.HashMap; import java.util.Map;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody;
/**
-
全局捕获异常 原理:使用AOP切面技术 捕捉返回json串 */ @ControllerAdvice(basePackages=“com.demo.controller”) public class ErrorUtil { //统一异常处理@ExceptionHandler,主要用于RuntimeException @ExceptionHandler(RuntimeException.class) @ResponseBody//返回json串 public Map<String, Object> errorResoult(){ Map<String, Object> errorMap= new HashMap<String, Object>(); errorMap.put(“errorCode”, “500”); errorMap.put(“errorMsg”, “系统错误”); return errorMap; } }
package com.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /**
-
全局捕获异常例子 @author hzz
*/ @RestController public class ErrorController {
//2)全局捕获异常 @RequestMapping("/test-error") public String testError(int a) { int b = 1/a; return "success"+b; }
}