使用事例:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@ControllerAdvice
public class ExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ExceptionHandler.class);
/**
* ParamException 为自定义异常类
* @param e 被springboot捕获到的ParamException
* @param req HttpServletRequest
* @return 返回自定义错误信息
*/
@org.springframework.web.bind.annotation.ExceptionHandler(ParamException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Error paramException(ParamException e, HttpServletRequest req) {
log.info("Remote host: {}, path: {}, illegal parameter", req.getRemoteHost(), req.getRequestURI(), e);
return new Error(e.getCode(), e.getMessage());
}
@org.springframework.web.bind.annotation.ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Error unknownException(Throwable e, HttpServletRequest req) {
log.error("Remote host: {}, path: {}, system exception", req.getRemoteHost(), req.getRequestURI(), e);
return new Error(ErrorCode.UNKNOWN_ERROR, e.getMessage());
}
}