【问题标题】:Spring send different response [closed]Spring发送不同的响应[关闭]
【发布时间】:2018-01-20 01:38:48
【问题描述】:

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

@RestController
public class MainController{

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

    }
}

【问题讨论】:

    标签: java spring rest model-view-controller


    【解决方案1】:

    你可以使用异常处理

    @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);
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多