本文共 1768 字,大约阅读时间需要 5 分钟。
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 MaphandlerNullPointException(){ Map 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;/** *处理404等error错误
* @author lius * */@Controllerpublic class errorController implements ErrorController { @Override public String getErrorPath() { // TODO Auto-generated method stub return "/error"; } @RequestMapping("/error") @ResponseBody public MaphandlerError(){ Map errMap = new HashMap<>(); errMap.put("code", 404); errMap.put("message", "404页面未找到!"); return errMap; }}
转载地址:http://innq.baihongyu.com/