Skip to content

Commit

Permalink
fix: Better error on input type missmatch (fix eemeli#459)
Browse files Browse the repository at this point in the history
  • Loading branch information
bambuchaAdm committed Jul 1, 2023
1 parent a442e95 commit 48b9bf9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/errors.ts
Expand Up @@ -25,6 +25,15 @@ export type ErrorCode =

export type LinePos = { line: number; col: number }

export class YAMLInputError extends Error {
constructor(message: string) {
super();
this.name = 'YAMLInputError'
this.message = message
}
}


export class YAMLError extends Error {
name: 'YAMLParseError' | 'YAMLWarning'
code: ErrorCode
Expand Down
10 changes: 9 additions & 1 deletion src/public-api.ts
@@ -1,7 +1,7 @@
import { Composer } from './compose/composer.js'
import type { Reviver } from './doc/applyReviver.js'
import { Document, Replacer } from './doc/Document.js'
import { prettifyError, YAMLParseError } from './errors.js'
import { prettifyError, YAMLParseError, YAMLInputError } from './errors.js'
import { warn } from './log.js'
import type { Node, ParsedNode } from './nodes/Node.js'
import type {
Expand Down Expand Up @@ -50,6 +50,10 @@ export function parseAllDocuments<
: Document<Contents, Strict>
>
| EmptyStream {
const inputType = typeof source;
if(inputType !== "string"){
throw new YAMLInputError(`Expected string, got ${inputType}`)
}
const { lineCounter, prettyErrors } = parseOptions(options)
const parser = new Parser(lineCounter?.addNewLine)
const composer = new Composer(options)
Expand Down Expand Up @@ -82,6 +86,10 @@ export function parseDocument<
): Contents extends ParsedNode
? Document.Parsed<Contents, Strict>
: Document<Contents, Strict> {
const inputType = typeof source;
if(inputType !== "string"){
throw new YAMLInputError(`Expected string, got ${inputType}`)
}
const { lineCounter, prettyErrors } = parseOptions(options)
const parser = new Parser(lineCounter?.addNewLine)
const composer = new Composer(options)
Expand Down
18 changes: 18 additions & 0 deletions tests/doc/parse.ts
Expand Up @@ -2,6 +2,7 @@ import { readFileSync } from 'fs'
import { resolve } from 'path'
import * as YAML from 'yaml'
import { source } from '../_utils'
import {YAMLInputError} from "../../src/errors";

describe('scalars', () => {
test('empty block scalar at end of document', () => {
Expand Down Expand Up @@ -819,3 +820,20 @@ describe('CRLF line endings', () => {
expect(res).toBe('foo bar')
})
})

describe('Errors on non string inputs', () => {
test('rise in parseDocument', () => {
const scenario = () => {
const input = Buffer.alloc(8)
YAML.parseDocument(input)
}
expect(scenario).toThrow(YAMLInputError)
})
test.todo('rise in parseAllDocuments', () => {
const scenario = () => {
const input = Buffer.alloc(8)
YAML.parseAllDocuments(input)
}
expect(scenario).toThrow(YAMLInputError)
})
})

0 comments on commit 48b9bf9

Please sign in to comment.