Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpServletResponse.sendError(int sc) vs HttpServletResponse.setStatus(int sc)

I use Spring mvc and my question is regarding the sendError method from HttpServletResponse.

Can someone please tell me which is best between:

@RequestMapping(method = RequestMethod.POST, produces = "application/json")
    public void createAdvertisement(@RequestBody @Validated(value = ValidationGroups.AdvertisementCreateUpdate.class) Advertisement advertisement, BindingResult bindingResult,
            HttpServletResponse response, @CurrentMember Member member) {
        if (bindingResult.hasErrors()) {
            response.setStatus(SC_BAD_REQUEST);
            return;
        }
        response.setStatus(SC_CREATED);
        advertisementService.createAdvertisement(member, advertisement);
    }

and that:

@RequestMapping(method = RequestMethod.POST, produces = "application/json")
    public void createAdvertisement(@RequestBody @Validated(value = ValidationGroups.AdvertisementCreateUpdate.class) Advertisement advertisement, BindingResult bindingResult,
            HttpServletResponse response, @CurrentMember Member member) {
        if (bindingResult.hasErrors()) {
            response.sendError(SC_BAD_REQUEST);
        }
        response.setStatus(SC_CREATED);
        advertisementService.createAdvertisement(member, advertisement);
    }

Notice that in the first code snippet, I set the status code and return whereas in the second one I use the sendError method.

Can someone please explain the pros and cons of both solutions?

like image 421
balteo Avatar asked Feb 16 '26 20:02

balteo


1 Answers

The main difference between the two is that sendError(int) sets and locks the response (you cannot change it after you call sendError) and it will display the error page.

The setStatus(int) method on the other hand allows you to alter the response after setting the status, plus it doesn't call the error page.

So basically use sendError if there is an error and you don't have to prepare a specific response and use setStatus for all other situations.

This is also explained in the Java EE documentation of the setStatus() method:

If this method is used to set an error code, then the container's error page mechanism will not be triggered. If there is an error and the caller wishes to invoke an error page defined in the web application, then sendError(int, java.lang.String) must be used instead.

like image 182
THelper Avatar answered Feb 19 '26 18:02

THelper