Exception: MultiJSON::ParseError

Inherits:
StandardError
  • Object
show all
Defined in:
lib/multi_json/parse_error.rb

Overview

Raised when JSON parsing fails

Wraps the underlying adapter’s parse error with the original input data, plus best-effort line and column extraction from the adapter’s error message. Line/column are populated for adapters that include them in their messages (Oj, the json gem) and remain nil for adapters that don’t (Yajl, fast_jsonparser).

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(message = nil, data: nil, cause: nil) ⇒ ParseError

Create a new ParseError

Examples:

ParseError.new("unexpected token at line 1 column 2", data: "{}")

Parameters:

  • message (String, nil) (defaults to: nil)

    error message

  • data (String, nil) (defaults to: nil)

    the input that failed to parse

  • cause (Exception, nil) (defaults to: nil)

    the original exception



57
58
59
60
61
62
63
64
# File 'lib/multi_json/parse_error.rb', line 57

def initialize(message = nil, data: nil, cause: nil)
  super(message)
  @data = data
  match = location_match(message)
  @line = match && Integer(match[1])
  @column = match && match[2] && Integer(match[2])
  set_backtrace(cause.backtrace) if cause
end

Instance Attribute Details

#columnInteger? (readonly)

The 1-based column reported by the adapter

Examples:

error.column  #=> 3

Returns:

  • (Integer, nil)

    column number, or nil if the adapter’s message did not include one



46
47
48
# File 'lib/multi_json/parse_error.rb', line 46

def column
  @column
end

#dataString? (readonly)

The input string that failed to parse

Examples:

error.data  #=> "{invalid json}"

Returns:

  • (String, nil)

    the original input data



28
29
30
# File 'lib/multi_json/parse_error.rb', line 28

def data
  @data
end

#lineInteger? (readonly)

The 1-based line number reported by the adapter

Examples:

error.line  #=> 1

Returns:

  • (Integer, nil)

    line number, or nil if the adapter’s message did not include one



37
38
39
# File 'lib/multi_json/parse_error.rb', line 37

def line
  @line
end

Class Method Details

.build(original_exception, data) ⇒ ParseError

Build a ParseError from an original exception

Examples:

ParseError.build(JSON::ParserError.new("..."), "{bad json}")

Parameters:

  • original_exception (Exception)

    the adapter’s parse error

  • data (String)

    the input that failed to parse

Returns:

  • (ParseError)

    new error with formatted message



74
75
76
# File 'lib/multi_json/parse_error.rb', line 74

def self.build(original_exception, data)
  new(original_exception.message, data: data, cause: original_exception)
end