SpringBoot全局统一异常处理(包含404错误处理)
1.ControllerAdvice&&ExceptionHandler处理异常
package com.lius.controllers; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/exception") public class testExceptionColtroller { @RequestMapping("/nullException") public String nullException() { //触发空指针异常 throw new NullPointerException("空指针异常!"); } }
package com.lius.handler; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice(basePackages = "com.lius.controllers") public class handlerException { @ExceptionHandler(NullPointerException.class) @ResponseBody private Map<String,Object> handlerNullPointException(){ Map<String,Object> map = new HashMap<>(); map.put("code", 500); map.put("message", "代码错误,空指针异常!"); return map; } }
2.ErrorController拦截处理404异常
package com.lius.controllers; import java.util.HashMap; import java.util.Map; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * <p>处理404等error错误</p> * @author lius * */ @Controller public class errorController implements ErrorController { @Override public String getErrorPath() { // TODO Auto-generated method stub return "/error"; } @RequestMapping("/error") @ResponseBody public Map<String,Object> handlerError(){ Map<String,Object> errMap = new HashMap<>(); errMap.put("code", 404); errMap.put("message", "404页面未找到!"); return errMap; } }
SpringBoot全局统一异常处理(包含404错误处理)
最新推荐文章于 2024-07-18 12:14:53 发布