gpt4 book ai didi

java - 我的自定义异常不返回异常代码(代码始终返回 500)

转载 作者:行者123 更新时间:2023-11-30 06:00:12 25 4
gpt4 key购买 nike

我有一个奇怪的问题。我构建了一个自定义异常类,并将该异常抛出到 try catch block 中。下面是我的代码示例。请帮我解决这个问题。这些是我的异常代码。

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;

}

以下是我的异常类

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

}

这是我抛出异常的地方。这是一个 RESTful Web API。但我总是在浏览器中遇到异常 500

if (agentService.findByNumberAndPin(agentNumber, pin) != null) {
if (dbsubscriber != null) {
throw new SubscriberAlreadyExistsException();
}

我无法弄清楚是什么导致了这个问题。任何快速帮助将不胜感激

最佳答案

您的自定义异常类errorCodeHTTP response code.完全不同

您需要在 REST Controller 中手动设置响应代码,例如:

response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

虽然这可行,但这可能是一种值得怀疑的做法。

关于java - 我的自定义异常不返回异常代码(代码始终返回 500),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52398174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com