我有一个奇怪的问题。我已经构建了一个自定义异常类,并在try catch块中抛出该异常。下面是我的代码示例。请帮我弄清楚这个问题。这些是我的例外代码。
public class DWExceptionCodes {
public static final int NO_AGENT_FOUND = 400;
public static final int AGENT_ALREADY_EXISTS = 401;
public static final int INCOMPLEATE_DATA = 402;
public static final int SUBSCRIBER_ALREADY_EXISTS = 403;
public static final int AGENT_VALIDATION_FAILED = 404;
public static final int NO_SUBSCRIBER_FOUND = 405;
public static final int TRANSACTION_FAILED = 409;
}
以下是我的Exception类
public class DWException 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 DWException(String errorMessage) {
super(errorMessage);
this.errorMessage = errorMessage;
}
public DWException(String errorMessage, int errorCode) {
super(errorMessage);
this.errorMessage = errorMessage;
this.errorCode=errorCode;
}
public DWException() {
super();
}
我创建了一个自定义异常,就是那个
public class SubscriberAlreadyExistsException extends DWException{
private static final long serialVersionUID = 1L;
private static String errorMessage = "Subscriber already exists";
private static int errorCode = DWExceptionCodes.SUBSCRIBER_ALREADY_EXISTS;
public SubscriberAlreadyExistsException() {
super(errorMessage, errorCode);
}
}
这是我抛出异常的地方。这是一个宁静的Web API。但总是我在浏览器中得到例外500
if (agentService.findByNumberAndPin(agentNumber, pin) != null) {
if (dbsubscriber != null) {
throw new SubscriberAlreadyExistsException();
}
我无法弄清楚导致这个问题的原因。任何快速帮助都很感激
您的自定义Exception类的errorCode
与HTTP response code.完全不同
您需要在REST控制器中手动设置响应代码,如:
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
虽然这可行,但这可能是一个值得怀疑的做法。
您的代码与发送回客户端的内容没有任何关联。
如果要从servlet发回特定的HTTP代码,请从HttpServletResponse中选择一个值,如下所示:
import javax.servlet.http.HttpServletResponse;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (agentService.findByNumberAndPin(agentNumber, pin) != null) {
if (dbsubscriber != null) {
// returns 403
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}