Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน assert.ifError() ใน Node.js

ฟังก์ชัน assert.ifError โยนข้อผิดพลาดหากค่าที่ส่งเข้ามา ไม่ใช่ null และไม่ใช่ undefined ใช้สำหรับตรวจสอบ error-first callback pattern

ไวยากรณ์

assert.ifError(value)

พารามิเตอร์

  • value – ค่าที่จะตรวจสอบ จะโยน error ในทุกกรณี ยกเว้น null หรือ undefined

ตัวอย่าง: ค่าที่ไม่ใช่ null/undefined

const assert = require('assert').strict;

try {
  assert.ifError('6'); // จะโยน error
} catch (error) {
  console.log("Error:", error);
}

ผลลัพธ์

Error: {
  AssertionError [ERR_ASSERTION]: ifError got unwanted exception: '6'
  ...
  operator: 'ifError'
}

ตัวอย่าง: ค่าเป็น null และ undefined

try {
  assert.ifError(null);
  console.log("No Error occurred");
  assert.ifError(undefined);
  console.log("OK");
} catch (error) {
  console.log("Error:", error);
}

ผลลัพธ์

No Error occurred
OK