在我的 GlobalExceptionHandler 中,我處理來自驗證器的例外。通常我會發送帶有錯誤的 json 回應,但有時我需要通過 thymeleaf 模式將錯誤作為 html 頁面發送。
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String constraintViolation(HttpServletResponse response, final Throwable throwable) throws WebApiException {
if (throwable.getMessage().startsWith("change")){
return "400";
}
String errMsg = throwable.getMessage().replaceAll(".*\\s?:\\s?(.*)$", "$1");
return new RestApiException(1007, errMsg).toString();
}
如果我使用 @ResponseBody 的所有回應作為純文本。但是對于條件“更改”,我想使用 thymeleaf 的 html 模板“400”。如何手動設定回應模式,有或沒有 @Responsebody 取決于條件。
謝謝
uj5u.com熱心網友回復:
而不是使用@ResponseBody你應該回傳ModelAndView。然后,您可以根據自己的情況選擇視圖。Thymeleaf 模板或Jackson 視圖將模型序列化為 JSON。
uj5u.com熱心網友回復:
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String constraintViolation(HttpServletRequest request, final Throwable throwable, Model model){
String errMsg = throwable.getMessage().replaceAll(".*\\s?:\\s?(.*)$", "$1");
if (!request.getHeader("Accept").startsWith("application/json")){
model.addAttribute("error", errMsg);
return "400";
}
String error = new RestApiException(1007, errMsg).toString();
model.addAttribute("error", error);
return "json";
}
和 thyamleaf 的 json 模式
[(${error})]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344084.html
