Spring发送不同的回复

时间:2017-08-11 13:48:16

标签: java spring rest model-view-controller

如果使用Spring Frameworks我有不同的错误,我如何发送不同的答案?

@RestController
public class MainController{

    @RequestMapping("/login")
    public Object login(){

    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用异常处理

@RequestMapping(value = "login", method = RequestMethod.POST)
@ResponseBody
public LoginResponse login(@RequestBody SignInRequest request) throws EmailNotValidException {
    if (isValidEmailAddress(request.getEmail())) throw new EmailNotValidException();

    return response;
}

之后,您可以使用@ExceptionHandler注释编写方法

    @ExceptionHandler({EmailNotValidException.class,DataAccessException.class})
    public ResponseEntity<BaseResponse> dummyExceptionHandler() {
         return new ResponseEntity<>(new BaseResponse("error"), HttpStatus.BAD_REQUEST);
    }