How to throw an exception back in JSON in Spring Boot

前端 未结 6 1352
-上瘾入骨i
-上瘾入骨i 2020-12-29 09:11

I have a Request Mapping -

  @RequestMapping(\"/fetchErrorMessages\")
  public @ResponseBody int fetchErrorMessages(@RequestParam(\"startTime\") String star         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 09:17

    Javax has a interface name as ExceptionMapper. Please refer the below code snippet, For every RuntimeException in your application it will map it to a Json Response entity.

    public class RuntimeExceptionMapper implements ExceptionMapper  {
    
    @Override
    public Response toResponse(RuntimeException exception) {
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(exception.getMessage);
        if (exception== null) {
            logger.error("Exception Details Not found");            
        } else {
            return Response.status(Status.INTERNAL_SERVER_ERROR)
                .entity(errorResponse )
                    .type(MediaType.APPLICATION_JSON)
                        .header("trace-id", "1234").build();
        }
    
    
    }
    

    }

提交回复
热议问题