简体   繁体   English

如何在使用 OnError 处理程序时从 REST 服务返回状态代码错误?

[英]How do I return a status code error from a REST Service while using an OnError handler?

I'm trying to set up some REST Web Services with ColdFusion 10, and if I have an onError handler in place in the Application.cfc the error status code is not returned back to to the Consumer.我正在尝试使用 ColdFusion 10 设置一些 REST Web 服务,如果我有一个 onError 处理程序未在 Application.cfc 中返回给消费者。

Let's consider this Application.cfc让我们考虑这个 Application.cfc

<cfcomponent displayname="ApplicationCFC" output="true" >
    <cfscript>
        this.name = "learnWith";
        this.applicationTimeout = createTimeSpan(1,1,0,0);
        this.sessionManagement = "false";
        this.restsettings.autoregister = true;
        this.restsettings.skipCFCWithError = true;
    </cfscript>

    <cffunction name="onApplicationStart" returntype="boolean" output="true">
        <cfset RestInitApplication(expandPath('/myDir'),"lw")>
        <cfreturn true>
    </cffunction>
</cfcomponent>

Now consider the service, like this:现在考虑服务,如下所示:

<cfcomponent rest="true" restpath="/user">
    <cffunction name="authenticate" access="remote" restpath="/login" returntype="String" httpmethod="POST"
            consumes="application/json" produces="application/json">
        <cfset requestData = getHTTPRequestData()>
        <cfset userInfo = deserializeJSON(ToString(requestData.content)) />

        <!--- cfquery to load user data ---->

        <cfif local.dataQuery.recordcount EQ 1>
            <cfset local.userVO = createObject()> <!--- create and populate userVo here --->
            <cfreturn SerializeJSON(local.userVO)>
        <cfelse>
            <!--- user not found, throw 401 error --->
            <cfthrow type="RestError" errorcode="401"  />
        </cfif>
    </cffunction>
</cfcomponent>

This code works perfectly from Postman.此代码从 Postman 完美运行。 If I pass in the proper credentials如果我传入正确的凭据

{
    "userName": "user",
    "password": "hashedPassword
}

I get a user object back as expected with a 200 response.我得到了一个用户 object 按预期返回 200 响应。

正确的凭据登录

If I pass in fake or invalid credentials:如果我传递虚假或无效的凭据:

{
    "userName": "fakeuser",
    "password": "fakePassword
}

I get a 401 error back:我收到一个 401 错误:

身份验证失败

That's perfect.那很完美。 However, I want to use a global error handler for the CFC, both for non-REST Service based code and to log possible REST Service errors.但是,我想为 CFC 使用全局错误处理程序,既用于基于非 REST 服务的代码,也用于记录可能的 REST 服务错误。 If I add this into the Application.cfc如果我将此添加到 Application.cfc

    <cffunction name="onError" returnType="void" output="true">
        <cfargument name="exception" required="true">
        <cfargument name="eventname" type="string" required="true">
        <!--- error logging here --->
        <cfthrow type="RestError" errorcode="401" />
        <!--- or 
            <cfthrow type="#arguments.exception.Cause.Cause.type#" 
                     errorcode="#arguments.exception.Cause.Cause.code#">--->

    </cffunction>

ColdFusion returns a 500 Internal Server error message. ColdFusion 返回 500 内部服务器错误消息。

500内部服务器错误

I experimented with cfheader both in the CFC method and within the onError handler:我在 CFC 方法和 onError 处理程序中都尝试了 cfheader:

<cfheader statusCode = "401" statusText = "RestError">

It'll return a 200 with no body instead of a 401 status:它将返回没有正文的 200 而不是 401 状态:

200 错误

I've tried various iterations of this, but am at a loss.我已经尝试过各种迭代,但不知所措。 Can I use status codes from a ColdFusion rest service while also having an onError handler in place?我是否可以使用来自 ColdFusion rest 服务的状态代码,同时还有一个 onError 处理程序? And if so, how?如果是这样,怎么办?

I was able to do what I want.我能够做我想做的事。 Instead of using cfthrow to create an error I can create the response I needed with restSetResponse .我可以使用 restSetResponse 创建所需的响应,而不是使用cfthrow创建错误。

Inside the cffunction, first make sure to set the return type to void.在 cffunction 中,首先确保将返回类型设置为 void。

Then instead of returning an object or using cfthrow, you want to create a response object manually and send it back using restSetResponse .然后,您希望手动创建响应 object 并使用 restSetResponse 将其发送回来,而不是返回 object 或使用restSetResponse

This solved my issue:这解决了我的问题:

<cfcomponent rest="true" restpath="/user">
    <cffunction name="authenticate" access="remote" restpath="/login" returntype="void" httpmethod="POST"
            consumes="application/json" produces="application/json">
        <cfset requestData = getHTTPRequestData()>
        <cfset userInfo = deserializeJSON(ToString(requestData.content)) />

        <!--- cfquery to load user data ---->

        <cfset local.result = structNew()/>

        <cfif local.dataQuery.recordcount EQ 1>
            <cfset local.userVO = createObject()> <!--- create and populate userVo here --->

            <cfset local.result.status = 200 />
            <cfset local.result.content = SerializeJSON(local.userVO) />
        <cfelse>
            <cfset local.result.status = 401 />
            <cfset local.result.content = SerializeJSON({message: 'User Not Authorized'}) />
        </cfif>

        <cfset restSetResponse(local.result) />
    </cffunction>
</cfcomponent>

Once I did that I was able to control the response back to my consumer without triggering the onError method in the Application.cfc .一旦我这样做了,我就能够控制对消费者的响应,而无需触发Application.cfc中的onError方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 既然WebServiceHost2Factory已经死了,我如何从WCF休息服务返回错误文本? - Now that WebServiceHost2Factory is dead, how do I return error text from a WCF rest service? 我应该何时从REST应用程序向客户端返回HTTP状态码500(内部服务器错误)? - When should I return HTTP Status Code 500 (Internal Server Error) from REST application to client? 如何从Rest Service返回错误消息 - How to return error message from rest service 如何从WCF REST方法返回自定义HTTP状态代码? - How can I return a custom HTTP status code from a WCF REST method? 使用 REST API 返回 HTTP 状态码 - Return HTTP status code using REST API 在基于Rest的Java Web应用程序中,从服务类返回http状态代码的正确方法是什么? - What is the proper way to return http status code from service class in a Rest based java web application? 是否为REST服务异步返回http状态代码202? - Asynchronously return http status code 202 for REST service? 如何从WCF REST服务返回包含二进制数据的结构? - How do I return a struct containing binary data from a WCF REST service? 休息后服务返回错误代码415 - Rest Post Service return error code 415 如何使用REST API更新VersionOne中资产的状态 - How do I update the status of an asset in VersionOne using the REST API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM