0

I'm trying to implement custom response message using this code:

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException ex) throws IOException {

        ErrorDetail errorDetail = ErrorDetail.NOT_FOUND;

        ErrorResponse errorEntry = new ErrorResponse();
        errorEntry.setTitle(errorDetail.getTitle());
        errorEntry.setCode(errorDetail.getErrorCode());
        HttpStatus httpStatus = ErrorDetail.getHttpStatusBasedOnErrorCode(errorDetail.getErrorCode());
        errorEntry.setStatus(httpStatus.value());
        errorEntry.setDetail(ex.getMessage());
        Map<String, String> extra = new HashMap<String, String>();
        extra.put("detail", ex.getMessage());
        errorEntry.setExtra(extra);

        ErrorResponseDTO errorResponse = new ErrorResponseDTO();
        errorResponse.setErrors(Arrays.asList(errorEntry));

        response.setStatus(errorDetail.getHttpStatus().value());
        String json = new ObjectMapper().writeValueAsString(errorResponse);
        response.getWriter().write(json);
        response.flushBuffer();
    }
}

I get this response:

{
    "errors": [
        {
            "status": 404,
            "code": "1000",
            "title": "Title not found",
            "detail": "Full authentication is required to access this resource",
            "source": null,
            "debugDetail": null,
            "extra": {
                "detail": "Full authentication is required to access this resource"
            }
        }
    ]
}

I can't find why I get the values:

"source": null,
"debugDetail": null,

I don't set these values anywhere. Do you know how I can remove them?

Full Github code:

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • This has to do with the configuration of your JSON mapper. The default configuration may include null properties in the generated JSON. Jackson? Have a look here: https://stackoverflow.com/questions/28324352/how-to-customise-the-jackson-json-mapper-implicitly-used-by-spring-boot? – bsaverino Jun 10 '20 at 20:56
  • Is there a way to remove at all `source` and `debugDetail`? – Peter Penzov Jun 10 '20 at 20:58
  • If you can modify ErrorResponse or use another response object, then yes. Otherwise, see my first comment. – bsaverino Jun 10 '20 at 21:05
  • I can modify ErrorResponse. Can you show me how I need to edit it? – Peter Penzov Jun 10 '20 at 21:20
  • I don't get it. Don't you know how to remove two member variables of a class? Or really I don't get it :) – bsaverino Jun 10 '20 at 21:50

0 Answers0