リクエストマッピングがあります -
@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ページが表示されます。
ホワイトラベルエラーページ
このアプリケーションには /error の明示的なマッピングがないため、これはフォールバックとして表示されます。
2017年12月20日水曜日10:49:37 IST
予期しないエラーが発生しました(タイプ=内部サーバーエラー、ステータス=500)。
日付時刻が無効です
代わりにJSONで500を返したいと思った
{"error":"Date time format is invalid"}
これについてどうすればいいでしょうか?
ベストアンサー1
NotFoundException
次のようなカスタム Exception クラスとその実装があるとします。
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();
}
}
ここで、コントローラーから例外をスローします。例外をスローする場合は、標準エラー ハンドラー クラスからキャッチする必要があります。たとえば、Spring では、クラスを標準エラー ハンドラーにするために適用するアノテーションが提供されています。これをクラスに適用すると、この Spring コンポーネント (つまり、アノテーションを付けたクラス) は、コントローラーからスローされた例外をキャッチできます。ただし、例外クラスを適切なメソッドにマップする必要があります。そのため、次のような@ControllerAdvice
例外ハンドラーでメソッドを定義しました。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
自動的に作成できます。