class Api::UserTokenController < Knock::AuthTokenController
  skip_before_action :verify_authenticity_token

  rescue_from Exception, :with => :return_error

  # Catch exception and return JSON-formatted error
  def return_error(exception)
    logger.error "==Handled======="
    logger.error exception.message
    logger.error exception.backtrace.join("\n")
    logger.error "==Handled=======" 
    case exception
    when ActiveRecord::RecordNotFound
      @status = 404
      @message = 'Record not found'
    when ActiveRecord::RecordInvalid
      @status = 422
      @message = 'Record invalid'
    when ArgumentError
      @status = 400
      @message = 'Argument Error'
    else
      @status = 500
      @message = 'Internal Error'
    end

    # for some reason render json_errors is not working
    # simulating JSON API support 
    render json: { 
      errors: [{
        status: @status.to_s,
        title: @message
      }]
    }
  end
end
