Spring Boot教程
SpringBoot使用ControllerAdvice和ExceptionHandler实现统一处理异常
package com.example.boot; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @ControllerAdvice public class ErrorHandler { @ExceptionHandler(Exception.class) @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String, Object> handle(HttpServletRequest req, Exception ex) { Map<String, Object> result = new HashMap<>(); result.put("errorCode", "404"); result.put("errorMsg", ex.getMessage()); return result; } }