/
2008-12-24-coldfusion-json-exception-handling.html
53 lines (39 loc) · 2.41 KB
/
2008-12-24-coldfusion-json-exception-handling.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
---
title: ColdFusion JSON Exception Handling
tags: javascript coldfusion
---
<p>When calling a ColdFusion end-point from an Ajax call, the caller is expecting a certain format. In my projects, that's usually JSON. Regardless, it would be nice if the caller could assume a constant format, even for exceptions.</p>
<p>Typically, when an exception is generated in ColdFusion, the server auto-generates an HTML description of the exception. The assumption is that a developer or an end-user will be looking at the resulting HTML.</p>
<p>But in our case, the caller is a script, and parsing that HTML would be a chore. Instead, we can leverage ColdFusion's CFERROR tag to make sure that even exceptions generate valid JSON. Then, the caller can handle the exception data, possibly merging the information into the UI.</p>
<p>You can setup an exception handler for you JSON API calls as follows. You would typically include this on an individual API page, or in the Application.cfm above all your APIs.</p>
<pre name="code" class="html">
<CFERROR type="exception" template="JSONExceptionSerializer.cfm">
</pre>
<p>Here is an example of how to handle the exception and format the results. You could also use a JSON library such as CFJSON or the tool that comes with CF8 to do the formatting.</p>
<pre name="code" class="html">
<CFSETTING showdebugoutput="no" enablecfoutputonly="yes">
<CFHEADER statuscode="500" statustext="">
<CFCONTENT reset="true">
<CFOUTPUT>
{
error: {
message: "#JSStringFormat(Error.message)#",
template: "#Error.TagContext[1].template#",
line: "#Error.TagContext[1].line#",
type: "#Error.RootCause.type#",
stacktrace: "#JSStringFormat(Error.StackTrace)#"
}
}
</CFOUTPUT>
<CFEXIT>
</pre>
<i>JSStringFormat() ensures that string content inside the JSON elements is properly escaped.</i>
<p>Extending this method, you can also manually throw exception in your ColdFusion code. For example, if the user is not logged in on the back-end, instead of doing this:</p>
<pre name="code" class="html">
<CFOUTPUT>Error: not logged in!</CFOUTPUT>
<CFEXIT>
</pre>
You can simply throw an exception.
<pre name="code" class="html">
<CFTHROW message="Not logged in!">
</pre>