简体   繁体   中英

How should behave rest controller when during a processing occur a error

I have question that interest me.

Assume that I have some rest controller and some rest client writing in javascript. This client send request to a controller and during a processing occur some error. How should behave controller in this situation? Should return null? or string with message?

For example, We have controller like this:

@RequestMapping("/user", method = RequestMethod.POST)
public @ResponseBody String createUser(User user) {

    try {
        userService.create(user);   
    } catch(UserCreationException e) {
    }
}

This is very simple example but is many different examples of controllers like controller which return some resources or only change state on the server side and I don't know what to do when occur error.

in improving developer(your consumers) experience , it is a good idea to respond with appropriate error messages on the response body in addition to the Http status code.

Here is an example with spring, mainly throw an exception that you can deal with by extending ResponseEntityExceptionHandler @ControllerAdvice

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException  extends RuntimeException{
    private static final long serialVersionUID = 1L;
    public ResourceNotFoundException(String message) {
        super(message);
    }

}

@Controller
@RequestMapping("/XXXXXs")
public class DoctypesController {
    @RequestMapping( method = RequestMethod.GET , value="/xxx")
    public  ResponseEntity<?> getXXXXXX(HttpServletRequest request) {
         if (XXX == null ) {
               throw new ResourceNotFoundException("XXXX Not found for);
           }else{
            response = buildResponse(xxxx)
           }

         return response;
    }
}


@ControllerAdvice
public class XXXXEntityExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(value = { ResourceNotFoundException.class })
protected ResponseEntity<Object> handleMissingResource(RuntimeException ex, final WebRequest request) {
HttpStatus status = HttpStatus.NOT_FOUND;
    return new ResponseEntity<Object>(new Error(String.valueOf(status.value()), status.getReasonPhrase(),ex.getMessage()),status);
    }
}

You should really use the HTTP Error codes and handle the HTTP error codes using your client-side technology, ie. JavaScript in your case.

For example: given a user who is unauthorised to read/access a Resource, then the 403 error code should be returned to the client. By using the standard HTTP/REST Error codes, you conform to an API that can be understood by any client, whether JavaScript or something else.

With Spring MVC and Rest controllers, it's really easy. Create a simple class for your Exception and annotate the class with the HTTP Error code, eg @ResponseStatus(value = HttpStatus.FORBIDDEN) for a 403 error. Then in your Controller, you can throw the exception which would in turn return the HTTP error code.

According http specifications , the server must return a error code >= 500 in case of internal error during processing.

If the error is caused because the client did a wrong request : the server must return a error code >= 400 and < 500

Of course, on client side you must take care to handle those errors properly (ie displaying a friendly error message or something like that).

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