我正在为我们的客户开发RESTful API 如果发生某些错误,我将显示错误信息 错误信息协议如下所示。
{
"status": "failure",
"error": {
"message": "",
"type": "",
"code": 0000
}
}
在编程层面,如何控制异常?
现在我已经制作了扩展Exception
类的自定义异常类。 (不是RuntimeException)
这种方法好不好?使用RuntimeExcepion会更好吗?
我的自定义异常类是......
public class APIException extends Exception {
public enum Code {
// duplicated exceptions
ALREADY_REGISTERED(1001),
// size exceptions
OVER_KEYWORD_LIMIT(2001),
OVER_CATEGORY_LIMIT(2002),
TOO_SHORT_CONTENTS_LENGTH(2003),
TOO_SHORT_TITLE_LENGTH(2004),
// database exceptions
DB_ERROR(3001),
// unregistered exceptions
UNREGISTERED_NAME(4001),
// missing information exceptions
MISSING_PARAMETER(5001),
// invalid information exceptions
INVALID_PARAMETER(6001),
INVALID_URL_PATTERN(6002);
private final Integer value;
private Code(Integer value) {
this.value = value;
}
public Integer getType() {
return value;
}
}
private final Code code;
public APIException(Code code) {
this.code = code;
}
public APIException(Code code, Throwable cause) {
super(cause);
this.code = code;
}
public APIException(Code code, String msg, Throwable cause) {
super(msg, cause);
this.code = code;
}
public APIException(Code code, String msg) {
super(msg);
this.code = code;
}
public Code getCode() {
return code;
}
}
使用像这样的APIException类......
public void delete(int idx) throws APIException {
try {
Product product = productDao.findByIdx(idx);
if (product.getCount() > 0) {
throw new APIException(Code.ALREADY_REGISTERED,
"Already registered product.");
}
productDao.delete(idx);
} catch (Exception e) {
throw new APIException(Code.DB_ERROR,
"Cannot delete product. " + e.getMessage());
}
}
哪个更好地制作自定义异常类或使用像illegalargumentexception这样的存在异常。
如果使自定义异常类更好,我应该在Exception或RuntimeException之间扩展什么?
请推荐我的好例子,例如我的情况
提前谢谢。
答案 0 :(得分:3)
由于你使用Spring,我建议:
扩展RuntimeException并让例外情况下降到控制器
如果您的异常类为要在错误XML中返回的属性建模,请注释该异常,以便它可以作为响应返回(如果它们都具有相同的状态代码,则包括@ResponseStatus
)
在控制器上实现一个或多个@ExceptionHandler
方法,以@ResponseBody
的形式返回异常,并确保HttpServletResponse正确无误。类似的东西:
@ExceptionHandler
@ResponseBody
public ErrorResponse handleAPIException(APIException e, HttpServletResponse response) {
// Set any response attributes you need...
return e; // or some other response
}