【发布时间】:2015-02-13 13:51:18
【问题描述】:
我正在尝试在 Spring-Boot 中为我的控制器编写错误处理程序,以捕获大多数可能的错误(Spring、sql 等)。到目前为止,我能够使用 Nulls 获得 JSON 响应,但是我无法将任何数据放入其中。当我尝试在其中收到错误消息时,我只收到一个空白页。
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
@RestController
public class BasicErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
@RequestMapping(value=ERROR_PATH)
@ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {
ErrorBody eBody = new ErrorBody();
eBody.setMessage(e.getCause().getMessage());
return eBody;
}
}
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ErrorBody {
private String dateTime;
private String exception;
private String url;
private String message;
}
【问题讨论】:
-
不确定您所说的“无法将任何数据放入其中”是什么意思 - 您做了什么,结果是什么?您不需要
ErrorController中的@ExceptionHandler注释(但您确实需要实现接口,而您的似乎不需要)。看看BasicErrorController在Spring Boot中是如何实现的,寻找线索。 -
实现
ErrorAttributes(不是ErrorController)可能会更好,但如果您想要完全控制,这是您的选择。 -
感谢您的回答。 “无法将任何数据放入其中”是指每当我尝试从错误 JSON 中获取任何数据时都不会显示。我今天解决了它,我能够通过使用“HttpServletRequest 请求”并从请求中读取信息来获取有关错误的数据并将它们正确地以 json 格式发送。
标签: spring spring-mvc error-handling spring-boot