<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jayesh Panchal on Medium]]></title>
        <description><![CDATA[Stories by Jayesh Panchal on Medium]]></description>
        <link>https://medium.com/@jspanchal?source=rss-2b7cbacbdde4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TBpeBa6Xkh30Hci-X98lAg.jpeg</url>
            <title>Stories by Jayesh Panchal on Medium</title>
            <link>https://medium.com/@jspanchal?source=rss-2b7cbacbdde4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:49:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jspanchal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Handling Express Errors Like A Boss]]></title>
            <link>https://medium.com/codetonics/handling-express-errors-like-a-boss-fd1985f90be4?source=rss-2b7cbacbdde4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd1985f90be4</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Jayesh Panchal]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 02:23:43 GMT</pubDate>
            <atom:updated>2020-08-18T02:26:01.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*eDKcHc5EmRUqXY3uYHddDw.png" /></figure><p>Error handling is a crucial aspect while developing any application for that matter. Since there wasn’t enough written answers I expected, so I had hard time figuring it out.</p><p>This article is kind of all in one article related to error handling aspect of Express framework.</p><p>So, Let’s begin with synchronous errors.</p><h3>Handling synchronous errors in Express</h3><p>This is simplest, just throw the error in an Express request handler.</p><pre>app.post(&#39;/health&#39;, (req, res) =&gt; {<br>  throw new Error(&#39;Destroyed in sync&#39;);<br>})</pre><p>By default express will handle the error with a default error handler if you don’t have a custom error handler. It will</p><ol><li>Set the status code to 500</li><li>Send the text response</li><li>Log the text response in the console</li></ol><h3>Handling asynchronous errors in Express</h3><p>In this case, it is not as simple as just throwing an error. You need to send the error into error handler (default/custom) through the next argument.</p><pre>app.post(&#39;/health&#39;, async (req, res, next) =&gt; {<br>  return next(new Error(&#39;Destroyed asynchronously&#39;));<br>})</pre><h3>Writing a custom error handler in Express</h3><p>The default error handler is good for nothing in production err but you can define a custom error handler which you should do always.</p><p>Express error handler take in four arguments:</p><ol><li>error</li><li>req</li><li>res</li><li>next</li></ol><p>and it must be placed after all middlewares and routes. eg.</p><pre>app.use(/* .. .*/);<br>app.get(/* ... */);<br>app.post(/* ... */);<br>app.put(/* ... */);<br>app.delete(/* ... */);</pre><pre>// Place your error handler after everything else<br>app.use((error, req, res, next) =&gt; { /* ... */ });</pre><p>Once you define a custom error handler, express will stop using the default one and use the custom one.</p><p>In your custom error handler, you will need to communicate the error with requester. You will need to following:</p><ol><li>Send a valid HTTP status code</li><li>Send a valid response stating the error</li></ol><pre>app.use((error, req, res, next) =&gt; {<br>  // Handling Bad request error<br>  res.status(/* status code */).json(/* error response */);<br>})</pre><h3>Handling 404 errors in Express</h3><p>Well, this deserves a separate section just because people tend to forget this all together. This is fairly simple, just insert a middleware between all routes and the error handler. Here is how</p><pre>app.use(/* ... */);<br>app.get(/* ... */);<br>app.post(/* ... */);<br>app.put(/* ... */);<br>app.delete(/* ... */);</pre><pre>// 404 middleware<br>app.user((req, res, next) =&gt; {<br>    const error = new Error(&#39;Page Not Found&#39;);<br>    const error.name = &#39;NOT_FOUND&#39;;<br>    return next(error);<br>});<br></pre><pre>// Place your error handler after everything else<br>app.use((error, req, res, next) =&gt; { <br>    switch(error.name){<br>        case &#39;NOT_FOUND&#39;:<br>            return res.status(404).json({message: &#39;Not Found&#39;});<br>        default:<br>            return res.status(500).json({message: &#39;Something Went Wrong&#39;});<br>    }<br>});</pre><h3>While streaming</h3><p>Well, this is the case when you will get ```Cannot set headers after they’re sent``’ error. This happens because the code ran methods that set response headers more than once in the same handler. In this case, Express says you should delegate the error to the default express handler. It will send the error and close the connection.</p><pre>app.use((error, req, res, next) =&gt; {<br>  // Do this only if you&#39;re streaming a response<br>  if (res.headersSent) {<br>    return next(error)<br>  }</pre><pre>  // Rest of the error handlers<br>})</pre><p>Happy error handling :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd1985f90be4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetonics/handling-express-errors-like-a-boss-fd1985f90be4">Handling Express Errors Like A Boss</a> was originally published in <a href="https://medium.com/codetonics">Codetonics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Battle between Slice and Splice in JavaScript]]></title>
            <link>https://medium.com/codetonics/battle-between-slice-and-splice-in-javascript-a54ead1f1d71?source=rss-2b7cbacbdde4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54ead1f1d71</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jayesh Panchal]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 08:26:03 GMT</pubDate>
            <atom:updated>2020-08-18T02:29:11.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTzbYqrI0DSo4o2vAkvDNw.jpeg" /></figure><p>Every once in a while one needs to play with part of an array and almost always end up looking for the difference between slice() and splice() first. Let’s clear the confusion between slice and splice in JavaScript.</p><h3>Array.prototype.slice</h3><p>The slice method returns <strong>a new array</strong> with a copied slice from the original array.</p><p>slice takes two optional parameters. The first is the beginning index and the second is the ending index. Well as I said both are optional, so if you don’t pass any parameter, you get a copy of original array.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>const copiedArray = originalArray.slice();<br>console.log(copiedArray); // [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;]</pre><p>if you provide one argument, you get copy of the original array from the specified index to the end of the array.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>const copiedArray = originalArray.slice(2);<br>console.log(copiedArray); // [&#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];</pre><p>The beginning index can also be negative, in that case the starting index is calculated from the end of the array.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>const copiedArray = originalArray.slice(-2);<br>console.log(copiedArray); // [&#39;john&#39;, &#39;doe&#39;]</pre><p>Here is an example with both the parameters.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>const copiedArray = originalArray.slice(1, 3);<br>console.log(copiedArray); // [&#39;bar&#39;, &#39;tuna&#39;];</pre><h3>Array.prototype.splice</h3><p>The splice method mutates the content of the array and used to add or remove items from the array.</p><p>When only first parameter is provided, all the items after the provided starting index are removed from the original array and returns the removed items.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>const copiedArray = originalArray.splice(2);<br>console.log(copiedArray); // [&#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>console.log(originalArray); // [&#39;foo&#39;, &#39;bar&#39;]</pre><p>The second parameter is for the number of items to remove from the original array.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;, &#39;john&#39;, &#39;doe&#39;];<br>const copiedArray = originalArray.splice(2, 1);<br>console.log(copiedArray); // [&#39;tuna&#39;];<br>console.log(originalArray); // [&#39;foo&#39;, &#39;bar&#39;, &#39;john&#39;, &#39;doe&#39;]</pre><p>You can also add items to the array using splice. You can pass any number of additional parameters after the second parameter which will be added to the array.</p><pre>const originalArray = [&#39;foo&#39;, &#39;bar&#39;, &#39;tuna&#39;];<br>const copiedArray = originalArray.splice(1, 0, &#39;john&#39;, &#39;doe&#39;);<br>console.log(copiedArray); // [&#39;tuna&#39;];<br>console.log(originalArray); // [ &#39;foo&#39;, &#39;john&#39;, &#39;doe&#39;, &#39;bar&#39;, &#39;tuna&#39; ]</pre><blockquote><em>slice is immutable while </em><em>splice mutates the array.</em></blockquote><p>In simple words splice() changes/mutates the original array where as slice() doesn’t and infact returns a new one. If you want to add items than only splice can do that between these two.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54ead1f1d71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetonics/battle-between-slice-and-splice-in-javascript-a54ead1f1d71">Battle between Slice and Splice in JavaScript</a> was originally published in <a href="https://medium.com/codetonics">Codetonics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async And Await in JavaScript]]></title>
            <link>https://medium.com/codetonics/async-and-await-in-javascript-ea62cccc4ba6?source=rss-2b7cbacbdde4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea62cccc4ba6</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jayesh Panchal]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 08:20:28 GMT</pubDate>
            <atom:updated>2020-08-18T02:31:26.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*DxgDQ83diwHf591x0zCLyw.jpeg" /></figure><p>There was a time asynchronous JavaScript was difficult. We used callbacks long enough, then came promises and now we have asynchronous functions.</p><p>Asynchronous functions make it easier to write asynchronous JavaScript. This article has everything about asynchronous functions you need to know.</p><h3>Asynchronous Functions in JavaScript</h3><p>An asynchronous function contains async keywords, rest is just like a normal function.</p><pre>const anAsyncFunction = async (arguments) =&gt; {<br>    // Do something asynchronously here<br>};</pre><p>Asynchronous functions returns promises. It doesn’t matter what you return from the function, the returned value will always be a promise.</p><pre>const incrementByOne = async (a) =&gt; {<br>    return a+1;<br>};</pre><pre>const returnedValue = incrementByOne(5); // Promise</pre><h3>Await</h3><p>When you call a promise, you handle the next step in a then call like this</p><pre>const incrementByOne = async (a) =&gt; {<br>    return a+1;<br>};</pre><pre>incrementByOne(5)<br>    .then(b =&gt; {<br>        console.log(b); // 6<br>    });</pre><p>This is where the await keyword comes into picture. The await lets you wait for the promise to resolve. Once the promise gets resolved, it returns the parameter passed into the then call.</p><pre>const incrementByOne = async (a) =&gt; {<br>    return a+1;<br>};</pre><pre>const b = await incrementByOne(5);<br>console.log(b); // 6</pre><h3>Error handling</h3><p>Well, use try catch</p><pre>const incrementByOne = async (a) =&gt; {<br>    return a+1;<br>};</pre><pre>const test = async () =&gt; {<br>    try{<br>        const b = await incrementByOne(5);<br>        console.log(b); // 6<br>    } catch(error){<br>        console.log(error);<br>    }   <br>};</pre><pre>test();</pre><p>or since an asynchronous function always returns a promise, you can use catch.</p><pre>const incrementByOne = async (a) =&gt; {<br>    return a+1;<br>};</pre><pre>const test = async () =&gt; {<br>    const b = await incrementByOne(5)<br>                        .catch(error =&gt; console.log(error));</pre><pre>    console.log(b); // 6<br>};</pre><pre>test();</pre><h3>Make it parallel</h3><p>await blocks JavaScript from executing the next line of code until a promise gets resolved. This can slow down the code execution when more than one functions can be called in parallel. The solution to this problem is simple. Don’t await. Instead store the returned promise in a variable and await at the end when the value is actually required.</p><p>Here is how</p><pre>const asyncOne = async () =&gt; {<br>    return 1;<br>};</pre><pre>const asyncTwo = async () =&gt; {<br>    return 2;<br>};</pre><pre>const asyncThree = async () =&gt; {<br>    return 3;<br>};<br></pre><pre>const test = async () =&gt; {<br>    const promiseOne = asyncOne();<br>    const promiseTwo = asyncTwo();<br>    const promiseThree = asyncThree();<br>    <br>    const one = await promiseOne;<br>    const two = await promiseTwo;<br>    const three = await promiseThree;<br>};</pre><pre>test();</pre><p>but this may not be ideal, If you await these three promises in a row, you’ll have to wait for three seconds before all three promises get resolved. This is not good because we forced JavaScript to wait two extra seconds before doing what we need to do.</p><p>Instead if you can fetch all three simultaneously, you will save extra two seconds.</p><p>To do that, you just need to store all the promises in an array and use Promise.all.</p><pre>const asyncOne = async () =&gt; {<br>    return 1;<br>};</pre><pre>const asyncTwo = async () =&gt; {<br>    return 2;<br>};</pre><pre>const asyncThree = async () =&gt; {<br>    return 3;<br>};<br></pre><pre>const test = async () =&gt; {<br>    const promiseArray = [asyncOne(), asyncTwo(), asyncThree()];<br>   <br>    const [one, two, three] = await Promise.all(promiseArray);<br>};</pre><pre>test();</pre><p>Wow, you saved precious time for JavaScript to do other things and also saved a lot of lines in code.</p><p>Keep Coding :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea62cccc4ba6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetonics/async-and-await-in-javascript-ea62cccc4ba6">Async And Await in JavaScript</a> was originally published in <a href="https://medium.com/codetonics">Codetonics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>