java 定义错误代码,在Java中定义错误代码/字符串的最佳方式?

本文探讨了在Java中为Web服务定义错误码和错误字符串的最佳实践。作者提出使用枚举类型来存储错误码和相关描述,并提供了优化的枚举实现方式,包括为每个错误定义独立的代码和描述,以及方便获取错误信息的方法。此外,还讨论了错误码的文档化和非国际化处理问题。
摘要由CSDN通过智能技术生成

I am writing a web service in Java, and I am trying to figure out the best way to define error codes and their associated error strings. I need to have a numerical error code and an error string grouped together. Both the error code and error string will be sent to the client accessing the web service. For example, when a SQLException occurs, I might want to do the following:

// Example: errorCode = 1,

// errorString = "There was a problem accessing the database."

throw new SomeWebServiceException(errorCode, errorString);

The client program might be shown the message:

"Error #1 has occured: There was a

problem accessing the database."

My first thought was to used an Enum of the error codes and override the toString methods to return the error strings. Here is what I came up with:

public enum Errors {

DATABASE {

@Override

public String toString() {

return "A database error has occured.";

}

},

DUPLICATE_USER {

@Override

public String toString() {

return "This user already exists.";

}

},

// more errors follow

}

My question is: Is there a better way to do this? I would prefer an solution in code, rather than reading from an external file. I am using Javadoc for this project, and being able to document the error codes in-line and have them automatically update in the documentation would be helpful.

解决方案

Well there's certainly a better implementation of the enum solution (which is generally quite nice):

public enum Error {

DATABASE(0, "A database error has occured."),

DUPLICATE_USER(1, "This user already exists.");

private final int code;

private final String description;

private Error(int code, String description) {

this.code = code;

this.description = description;

}

public String getDescription() {

return description;

}

public int getCode() {

return code;

}

@Override

public String toString() {

return code + ": " + description;

}

}

You may want to override toString() to just return the description instead - not sure. Anyway, the main point is that you don't need to override separately for each error code. Also note that I've explicitly specified the code instead of using the ordinal value - this makes it easier to change the order and add/remove errors later.

Don't forget that this isn't internationalised at all - but unless your web service client sends you a locale description, you can't easily internationalise it yourself anyway. At least they'll have the error code to use for i18n at the client side...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值