我有以下错误类:
private static class GenericError extends Error {
private int code;
private String message;
private Date timestamp;
public GenericError(String message, int code, String message1) {
super(message);
this.code = code;
this.message = message1;
this.timestamp = new Date();
}
public int getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
public Date getTimestamp() {
return timestamp;
}
}
private static class ConfirmResponse extends GenericError {
private String confirmMessage;
private String instructions;
public ConfirmResponse(String message, int code, String message1, String confirmMessage, String instructions) {
super(message, code, message1);
this.confirmMessage = confirmMessage;
this.instructions = instructions;
}
public String getConfirmMessage() {
return confirmMessage;
}
public String getInstructions() {
return instructions;
}
}
我正在使用它:
@RequestMapping(value="login", method=RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
FbLoginResponse login(@RequestBody Body body) throws IOException, InvalidKeySpecException,
NoSuchAlgorithmException, ConfirmLogin, ClassNotFoundException, ConfirmResponse {
...
...
...
...
ConfirmResponse r = new ConfirmResponse("Error", 111, "An account already exists under this email",
"Please confirm your account",
"Log in with your prev account");
throw r;
但我得到的回答不正确:
{
"timestamp": 1467604509746,
"status": 500,
"error": "Internal Server Error",
"exception": "com.userapi.spring.controller.UserController$ConfirmResponse",
"message": "An account already exists under this email",
"path": "/user/login/fac
ebook"
}
我还尝试扩展 例外 ,这会产生相同的消息。
我希望能够将多个不同的 类对象 返回给客户端。所以,如果出现错误,我可以返回
new Error("Error occured")
如果我需要返回我可以做的自定义消息
return new CustomMessage("Check your Email!);
当我定义控制器的返回类型时,我不能这样做,例如
LoginResp login(@RequestBody UserFacebookLoginContext body)
... I can only return LoginResp, I cannot return ErrorResponse, or CustomResponse
基本上我想要的是返回多种类型的类,例如
AnyResp login(@RequestBody UserFacebookLoginContext body)
if error ... return new ErrorResponse("something went wrong");
if requires-custom ... return new CustomResponse ("Please check your email");
答案 0 :(得分:2)
我将给你一个例子,说明我如何使用ResponseEntity
来处理不同的对象
@RequestMapping(value = "/all", method = RequestMethod.GET)
public ResponseEntity<?> getAll() {
List<Transferencia> list = transferenciaDAO.getAll();
if (!list.isEmpty()) {
return new ResponseEntity<>(list, HttpStatus.OK);
} else {//here you can return any type of object doing your respective control of field.
JsonResponse msj = new JsonResponse("Error", "List empty");
return new ResponseEntity<>(msj, HttpStatus.NOT_FOUND);
}
}
如果您不想返回任何错误。你可以返回类似的东西:
return new ResponseEntity<>(HttpStatus.NOT_FOUND);