简体   繁体   中英

Do i need to catch NullPointerException in rest controller?

I know NPE is an unchecked (RTE), and as such we need to prevent it from happening rather than catching it: https://www.javaworld.com/article/2072719/effective-java-nullpointerexception-handling.html

But still, let's say I have a REST controller that returns an employee record upon a request. That depends on finding the underlying employee record in the DB before doing update. See the example below:

@RequestMapping(value = BENEFIT_VERSION, method = GET)
@PreAuthorize(READ_COMPANY_DATA)
public ResponseEntity get(@PathVariable UUID employerId,
                              @PathVariable Long versionId) {
    log.info("Request to fetch benefit version, employerId: {}, versionId: {}", employerId, versionId);

    BenefitVersion benefitVersion = benefitVersionService.findByEmployerIdAndId(employerId, versionId); <--- Here NPE may be thrown

    if (benefitVersion == null) {
        log.warn("Unable to fetch non-existent benefit version, employerId: %s, ID: %s", employerId, versionId);
        return new ResponseEntity(NOT_FOUND);
    }

    RestBenefitVersion restBenefitVersion = restBenefitVersionAssemblerFacade.toResource(benefitVersion);

    return new ResponseEntity<>(restBenefitVersion, OK);
}

The benefitVersionService.findByEmployerIdAndId(employerId, versionId) bit may throw NPE.

There is no handler for the NPE associated with this controller, so NPE will simply kill the request processing. Is that all right or would be better to provide a NPE handler for this case to return a meaningful response to the client instead?

It is best practice to handle, and provide meaningful message to client side. REST frameworks usually provides way to configure exception handlers, and mappers. Check this for Spring. You can find similar mechanism for your REST framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM