spring-projects / spring-projects/spring-data-rest

Handle errors from @RestResource [DATAREST-1281]

Open
#1,642 0 comments 0 reactions 1 assignee View on GitHub

@odrotbohm is already working on this.

Since Dec 31, 2020.

type: bug
Dominant language
Java
Stars
958
Forks
568
PR merge metrics
No merged PRs in 30d

Description

Jérémie Campari opened DATAREST-1281 and commented

I use @RestResource in my Spring Data Rest web application to generate endpoints. And I would like to custom 404 error on findById() endpoint to add a JSON body to the response.

I'm aware of ControlerAdvice, handler... BUT it doesn't work with RestResource.

After more research in spring source code I find the code below. It seems that if entity is not found, no exception is raised, RestResource just returned a new ResponseEntity>(HttpStatus.NOT_FOUND)). So it seems impossible to handle and customize the Not Found error with RestResource ?

 

Code from org.springframework.data.rest.webmvc.RepositoryEntityController

    /**
     * <code>GET /{repository}/{id}</code> - Returns a single entity.
     * 
     * @param resourceInformation
     * @param id
     * @return
     * @throws HttpRequestMethodNotSupportedException
     */
    @RequestMapping(value = BASE_MAPPING + "/{id}", method = RequestMethod.GET)
    public ResponseEntity<Resource<?>> getItemResource(RootResourceInformation resourceInformation,
            @BackendId Serializable id, final PersistentEntityResourceAssembler assembler, @RequestHeader HttpHeaders headers)
            throws HttpRequestMethodNotSupportedException {

        return getItemResource(resourceInformation, id).map(it -> {

            PersistentEntity<?, ?> entity = resourceInformation.getPersistentEntity();

            return resourceStatus.getStatusAndHeaders(headers, it, entity).toResponseEntity(//
                    () -> assembler.toFullResource(it));

        }).orElseGet(() -> new ResponseEntity<Resource<?>>(HttpStatus.NOT_FOUND));
    }

Handle and customize errors is a must have from my point of view


Affects: 3.0.9 (Kay SR9)

Reference URL: https://stackoverflow.com/questions/52201934/how-to-handle-exception-from-spring-data-rest-resource?noredirect=1#comment91353608_52201934

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.