Home > Mobile >  response json in body or thymeleaf template depend of condition
response json in body or thymeleaf template depend of condition

Time:10-31

In my GlobalExceptionHandler I process my exceptions from validator. Usually I send json response with error but sometimes I need to send error as html page by thymeleaf pattern.

@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();
    }

If I use @ResponseBody everythig response as plaint text. But for condition "change", I wanna use html template "400" by thymeleaf. How to set response mode manually, with or without @Responsebody depends on condition.

Thx

CodePudding user response:

Rather than using @ResponseBody you should return ModelAndView. Then you can, based on your condition, choose the view. Either Thymeleaf template or Jackson view to serialize the model to JSON.

  • Related