用java开发RESTful API时如何控制异常? [英] How to control exception while developing RESTful API with java?

查看:23
本文介绍了用java开发RESTful API时如何控制异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们的客户开发 RESTful API.
如果发生错误,我将显示错误信息.
错误信息协议如下所示.

I'm developing RESTful API for our clients.
I'm about to show error information if some error occurs.
The error information protocol look like below.

{ 
    "status": "failure",
    "error": {
        "message": "", 
        "type": "",
        "code": 0000 
    } 
} 

在编程层面,如何控制异常?
现在我已经制作了扩展 Exception 类的自定义异常类.(不是运行时异常)
这种方法好不好?使用 RuntimeExcepion 更好吗?
我的自定义异常类是...

In programming level, how to controll exceptions?
Now I've made custom exception class extending Exception class. (not RuntimeException)
Is this approach good or not? Is it better using RuntimeExcepion?
My custom exception class is ...

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 类...

And using APIException class like this...

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

哪个更好地制作自定义异常类或使用像非法参数异常这样的存在异常..
如果自定义异常类更好,我应该在 Exception 或 RuntimeException 之间扩展什么?
请向我推荐像我这种情况的好例子.
提前致谢.

Which is better make custom exception class or using exist exception like illegalargumentexception..
If making custom exception class is better, what should I extend among Exception or RuntimeException?
Please recommend me good example like my situation.
Thanks in advance.

推荐答案

由于您使用的是 Spring,我建议:

Since you're using Spring, I'd recommend:

  1. 扩展 RuntimeException 并让异常进入控制器

  1. Extending RuntimeException and letting the exceptions drop through to the controller

如果您的异常类对要在错误 XML 中返回的属性进行建模,请对异常进行注释,以便它可以作为响应返回(包括 @ResponseStatus,如果它们都具有相同的状态码).

If your exception class models the attributes you want to return in your error XML, annotate the exception so it can be returned as a response (including a @ResponseStatus if they all have the same status code).

在您的控制器上实现一个或多个 @ExceptionHandler 方法,该方法将异常作为 @ResponseBody 返回并确保 HttpServletResponse 正确.类似的东西:

Implement one or more @ExceptionHandler methods on your controller that returns the exception as the @ResponseBody and ensures the HttpServletResponse is correct. Something like:

@ExceptionHandler
@ResponseBody
public ErrorResponse handleAPIException(APIException e, HttpServletResponse response) {
// Set any response attributes you need...
    return e; // or some other response
}

这篇关于用java开发RESTful API时如何控制异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆