feat: add error handling for duplicate or not exists

This commit is contained in:
wancat committed 2023-08-21 22:22:01 +08:00
1 parent 9b78f0d41c
commit 5a1fc6499a
3 files changed
+86 -56

No files matched your search

+9 -6
View File
@@ -1,5 +1,6 @@
import path from 'path'
import File from './file.js'
import { DuplicateItemError, ParentNotExistsError } from './errors.js'
export default class FileNode extends File {
constructor(file) {
@@ -10,7 +11,11 @@ export default class FileNode extends File {
addChild(fileInput) {
const file = new File(fileInput)
if (file.path === this.path) {
throw new Error('File already exists in the tree')
throw new DuplicateItemError('File already exists in the tree')
}
if (this.children.some((child) => child.path === file.path)) {
throw new DuplicateItemError('File already exists in the tree')
}
const parentPath = path.dirname(file.path)
@@ -23,19 +28,17 @@ export default class FileNode extends File {
if (childNode) {
childNode.addChild(file)
} else {
console.log(fileInput, this)
throw new Error('Parent path not found in the tree')
throw new ParentNotExistsError('Parent path not found in the tree')
}
}
}
toString() {
const indent = ' '.repeat(this.path.split('/').length - 1)
const suffix = this.isDirectory() ? '/' : ''
const childrenString = this.children
.map((child) => child.toString())
.join('')
return `${indent}${this.name}${
this.isDirectory() ? '/' : ''
}\n${childrenString}`
return `${indent}${this.name}${suffix}\n${childrenString}`
}
}