# エラーハンドリング

配列を受け取り、カンマで区切って文字列にする関数があるとします。この関数の引数に文字列を渡すとエラーが発生します。エラーが発生する原因として、文字列型は`join`というメソッドを持っていないため、メソッドを呼び出すことができずエラーとなります。このような場合、内部的に**throw文**が使用されます。**throw文**は例外を発生させ、そこで処理が止まります。

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
console.log(numbers.map((num) => num * 3)); // [3, 6, 9, 12]
<strong>const splitString = (str) => {
</strong><strong>    return str.split(",");
</strong><strong>};
</strong><strong>console.log(splitString("a,b,c")); // ['a', 'b', 'c']
</strong><strong>console.log(splitString(1)); // Uncaught TypeError: str.split is not a function
</strong></code></pre>

この例外を検知する方法として、**try\~catch文**というものがあります。**try\~catch文**は`try`の中に記載した処理にて、例外処理が発生した場合に、`catch`の中の処理が処理されます。

`catch(e)`の`e`は例外処理が発生した場合の例外の内容が格納されます。

通常例外処理が発生すると、`throw new Error('エラーメッセージ')`のように**Errorコンストラクター**から、**Errorオブジェクト**を生成します。この**Errorオブジェクト**を`e`にて受け取ることができます。

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
console.log(splitString("a,b,c")); // ['a', 'b', 'c']
<strong>try {
</strong><strong>    console.log(splitString(1));
</strong><strong>} catch(e) {
</strong><strong>    alert(e);
</strong><strong>}
</strong></code></pre>

ちなみ`alert`メソッドは、ブラウザ上部にポップアップを表示するメソッドで、以下のように表示されます。

<figure><img src="https://1869761657-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcUBbYqol4PMzZJggiMqV%2Fuploads%2FcuGMMT7YzjKyD7nhToEK%2F%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%202023-12-01%2017.49.25.png?alt=media&#x26;token=1a0a1d8d-d057-4f81-ae39-c250d335d295" alt=""><figcaption></figcaption></figure>

現在内部的に`throw`していますが、明示的に`throw`するようにしましょう。

<pre class="language-javascript" data-title="index.js◎"><code class="lang-javascript">...
const splitString = (arr) => {
<strong>    if (typeof arr !== 'string') {
</strong><strong>        throw new Error('value is not a string.');
</strong><strong>    }
</strong>    return arr.join(',');
};
...
</code></pre>

以下のようにエラー分が変わったかと思います。

<figure><img src="https://1869761657-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FcUBbYqol4PMzZJggiMqV%2Fuploads%2FZuhVEAExmd1aJh4Mdpne%2F%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%202023-12-01%2017.54.12.png?alt=media&#x26;token=de45114f-a26a-4c2b-83c7-267ef0dd4170" alt=""><figcaption></figcaption></figure>
