@RestController
@CrossOrigin(origins = "*")
public class MemberController {
@Autowired
memberinfoservice memberinfoservice;
@RequestMapping(value="/getMemberID/", method=RequestMethod.POST ,headers = "Accept=application/json")
public ResponseMemberID getMemberID(@RequestBody RequestMemberID request) throws Exception{
Member_info memberinfo = new Member_info();
ResponseMemberID _response =new ResponseMemberID();
memberinfo = memberinfoservice.getMemberID(request.getPin(),request.getMsisdn());
if(memberinfo == null) {
throw new PINNotValidException();
}
_response.setMember_id(memberinfo.getMember_id());
return _response;
}
@ExceptionHandler(PINNotValidException.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
ErrorResponse error = new ErrorResponse();
error.setErrorCode(PSAExceptionCodes.PIN_VALIDATION_FAIL);
error.setMessage(ex.getMessage());
return new ResponseEntity<ErrorResponse>(error, HttpStatus.OK);
}
上面提到的是我根据链接http://www.jcombat.com/spring/exception-handling-in-spring- restful-web-service更改的代码,它满足了我的问题。
此外,我还尝试在我创建的应用程序中使用 类的 方法,但该方法始终返回空响应。
但是通过在创建单独的 PINNotValidException.class , ErrorResponse.class ,PSAException.class 和 PSAExceptionCodes.class 时使用@ExceptionHandler作为自定义异常,我可以轻松解决我的问题。下面分别提到了这些类。
public class PINNotValidException extends PSAException{
private static final long serialVersionUID = 1L;
private static String errorMessage = "Pin Number and Mobile Number mismatch.";
private static int errorCode = PSAExceptionCodes.PIN_VALIDATION_FAIL;
public PINNotValidException() {
super(errorMessage, errorCode);
}
}
public class ErrorResponse {
private int errorCode;
private String message;
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public class PSAException extends Exception {
private static final long serialVersionUID= 100L;
private String errorMessage;
private int errorCode;
public String getErrorMessage() {
return errorMessage;
}
public int getErrorCode(){
return errorCode;
}
public PSAException(String errorMessage) {
super(errorMessage);
this.errorMessage = errorMessage;
}
public PSAException(String errorMessage, int errorCode) {
super(errorMessage);
this.errorMessage = errorMessage;
this.errorCode=errorCode;
}
public PSAException() {
super();
}
}
public class PSAExceptionCodes {
public static final int PIN_VALIDATION_FAIL = 251; //Pin and mobile mismatch
public static final int ACCOUNT_TYPE_NOT_FOUND = 300; //Account type mismatch
public static final int NO_MEMBER_FOUND = 250; //Member Not Found
public static final int MEMBER_NOT_REGISTERED = 256; //Member not registered
}