我有一个请求映射 -
@RequestMapping("/fetchErrorMessages")
public @ResponseBody int fetchErrorMessages(@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime) throws Exception
{
if(SanityChecker.checkDateSanity(startTime)&&SanityChecker.checkDateSanity(endTime))
{
return 0;
}
else
{
throw new NotFoundException("Datetime is invalid");
}
}
如果 startTime 和 endTime 无效,我想抛出 500 错误,但返回 JSON 中的异常字符串。但是,我得到一个 HTML 页面而不是说
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Dec 20 10:49:37 IST 2017
There was an unexpected error (type=Internal Server Error, status=500).
Datetime is invalid
我反而想用 JSON 返回 500
{"error":"Date time format is invalid"}
我该怎么做?
最佳答案
假设您有一个自定义异常类 NotFoundException
及其实现如下所示:
public class NotFoundException extends Exception {
private int errorCode;
private String errorMessage;
public NotFoundException(Throwable throwable) {
super(throwable);
}
public NotFoundException(String msg, Throwable throwable) {
super(msg, throwable);
}
public NotFoundException(String msg) {
super(msg);
}
public NotFoundException(String message, int errorCode) {
super();
this.errorCode = errorCode;
this.errorMessage = message;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
@Override
public String toString() {
return this.errorCode + " : " + this.getErrorMessage();
}
}
现在你想从 Controller 中抛出一些异常。如果你抛出一个异常,那么你必须从一个标准的错误处理程序类中捕获它,例如在 Spring ,他们提供了 @ControllerAdvice
注释来申请一个类标准错误处理程序。当它应用于一个类时,这个 spring 组件(我的意思是你注释的类)可以捕获从 Controller 抛出的任何异常。但是我们需要用适当的方法映射异常类。所以我们用你的异常 NotFoundException
处理程序定义了一个方法,如下所示。
@ControllerAdvice
public class RestErrorHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Object processValidationError(NotFoundException ex) {
String result = ex.getErrorMessage();
System.out.println("###########"+result);
return ex;
}
}
您想将http 状态发送到内部服务器错误(500),所以这里我们使用了@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
。由于您使用的是 Spring-boot,因此您不需要制作 json 字符串,除了简单的注释 @ResponseBody
可以自动为您完成。
关于java - 如何在 Spring Boot 中以 JSON 形式抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47899292/