Format task result to json output in jsend specification format. See:
    https://github.com/omniti-labs. Task return value must be dict or None.

    @param fail_exception_classes: exceptions which will produce 'fail' response
    status.
546802
def jsend_output(fail_exception_classes=None):
    

    fail_exception_classes = fail_exception_classes if fail_exception_classes \
        else ()

    def decorator_fn(f):

        @wraps(f)
        @json_output
        def jsend_output_decorator(*args, **kwargs):
            try:
                rv = f(*args, **kwargs)
            except fail_exception_classes as e:
                return {'status': 'fail', 'data': {'message': str(e)}}
            except Exception as e:
                logging.error(str(e) + "\n" + traceback.format_exc())
                return {'status': 'error', 'message': 'Server error.'}

            if not isinstance(rv, dict) and rv is not None:
                msg = 'jsend_output decorator error: task must return dict ' \
                      'or None.\nTask return value: {0}.'
                logging.error(msg.format(rv))
                return {'status': 'error', 'message': 'Server error.'}

            return {'status': 'success', 'data': rv}

        return jsend_output_decorator

    return decorator_fn
271459
def internal_get_exception_details_json(dbg, request, thread_id, max_frames, set_additional_thread_info=None, iter_visible_frames_info=None):
    ''' 
    '''
    try:
        response = build_exception_info_response(dbg, thread_id, request.seq, set_additional_thread_info, iter_visible_frames_info, max_frames)
    except:
        exc = get_exception_traceback_str()
        response = pydevd_base_schema.build_response(request, kwargs={
            'success': False,
            'message': exc,
            'body':{}
        })
    dbg.writer.add_command(NetCommand(CMD_RETURN, 0, response, is_json=True))
1374684
private JSONNavi<?> failure(String err, Object jPathPostfix) {
		failure = true;
		StringBuilder sb = new StringBuilder();
		sb.append("Error: ");
		sb.append(err);
		sb.append(" at ");
		sb.append(getJPath());
		if (jPathPostfix != null)
			if (jPathPostfix instanceof Integer)
				sb.append('[').append(jPathPostfix).append(']');
			else
				sb.append('/').append(jPathPostfix);
		this.failureMessage = sb.toString();
		return this;
	}
4869
def process_failure(project):
    
    if failure:
        lists = get_lists.GetLists()
        report_url = lists.report_url(project)
        if report_url:
            print(report_url)
        sys.exit(1)
1320332
def json_error_handler(exception):
    
    http_exception = isinstance(exception, exceptions.HTTPException)
    code = exception.code if http_exception else 500

    # log exceptions only (app debug should be off)
    if code == 500:
        current_app.logger.error(exception)

    response = jsonify(dict(message=str(exception)))
    response.status_code = code
    return response
80544
def lambda_failure_response(*args):
        
        response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
        return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
1260276
@Override
	public void onTaskFailure(Execution taskExecution, Throwable cause) {

		executionGraph.getJobMasterMainThreadExecutor().assertRunningInMainThread();

		// to better handle the lack of resources (potentially by a scale-in), we
		// make failures due to missing resources global failures 
		if (cause instanceof NoResourceAvailableException) {
			LOG.info("Not enough resources to schedule {} - triggering full recovery.", taskExecution);
			executionGraph.failGlobal(cause);
			return;
		}

		LOG.info("Recovering task failure for {} (#{}) via individual restart.", 
				taskExecution.getVertex().getTaskNameWithSubtaskIndex(), taskExecution.getAttemptNumber());

		numTaskFailures.inc();

		// trigger the restart once the task has reached its terminal state
		// Note: currently all tasks passed here are already in their terminal state,
		//       so we could actually avoid the future. We use it anyways because it is cheap and
		//       it helps to support better testing
		final CompletableFuture<ExecutionState> terminationFuture = taskExecution.getTerminalStateFuture();
		terminationFuture.thenRun(
			() -> performExecutionVertexRestart(taskExecution.getVertex(), taskExecution.getGlobalModVersion()));
	}
290141
def _fail(response):
        
        message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url)
        try:
            message += ", message:{}".format(response.json()["message"])
        except (ValueError, KeyError):
            pass
        raise ApiFailure(message, response.status_code)
322839
public String getJsonError(ODataException exception) throws ODataRenderException {
        checkNotNull(exception);

        LOG.debug("Start building Json error document");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            JsonGenerator jsonGenerator = JSON_FACTORY.createGenerator(outputStream, JsonEncoding.UTF8);
            jsonGenerator.writeStartObject();

            jsonGenerator.writeObjectFieldStart(ERROR);

            jsonGenerator.writeStringField(CODE, String.valueOf(exception.getCode().getCode()));
            jsonGenerator.writeStringField(MESSAGE, String.valueOf(exception.getMessage()));
            // optional
            if (exception.getTarget() != null) {
                jsonGenerator.writeStringField(TARGET, String.valueOf(exception.getTarget()).replace("\"", "'"));
            }
            jsonGenerator.writeEndObject();
            jsonGenerator.close();

            return outputStream.toString();
        } catch (IOException e) {
            LOG.error("Not possible to write error JSON.");
            throw new ODataRenderException("Not possible to write error JSON: ", e);
        }
    }
18053
def task_status(request, task_id):
    """"""
    result = AsyncResult(task_id)
    state, retval = result.state, result.result
    response_data = {'id': task_id, 'status': state, 'result': retval}
    if state in states.EXCEPTION_STATES:
        traceback = result.traceback
        response_data.update({'result': safe_repr(retval),
                              'exc': get_full_cls_name(retval.__class__),
                              'traceback': traceback})
    return JsonResponse({'task': response_data})
817945
def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any:
    
    if isinstance(result, dict):
        if result.get('status') == 'failed':
            raise ActionFailed(retcode=result.get('retcode'))
        return result.get('data')
833412
public void toJson(JsonWriter jsonWriter, boolean keepConfig) throws IOException {
    jsonWriter.beginObject();

    jsonWriter.name("task id").value(this.getTaskId()).name("task state").value(this.getWorkingState().name())
        .name("start time").value(this.getStartTime()).name("end time").value(this.getEndTime()).name("duration")
        .value(this.getTaskDuration()).name("retry count")
        .value(this.getPropAsInt(ConfigurationKeys.TASK_RETRIES_KEY, 0));

    // Also add failure exception information if it exists. This information is useful even in the
    // case that the task finally succeeds so we know what happened in the course of task execution.
    if (getTaskFailureException().isPresent()) {
      jsonWriter.name("exception").value(getTaskFailureException().get());
    }

    if (keepConfig) {
      jsonWriter.name("properties");
      jsonWriter.beginObject();
      for (String key : this.getPropertyNames()) {
        jsonWriter.name(key).value(this.getProp(key));
      }
      jsonWriter.endObject();
    }

    jsonWriter.endObject();
  }
958673
@SuppressWarnings("deprecation")
  public void failedTask(
    TaskInProgress tip,
    TaskAttemptID taskid,
    String reason,
    TaskStatus.Phase phase,
    boolean isFailed,
    String trackerName,
    TaskTrackerInfo ttStatus) {
    TaskStatus.State state =
      isFailed ? TaskStatus.State.FAILED: TaskStatus.State.KILLED;
    TaskStatus status = TaskStatus.createTaskStatus(tip.isMapTask(),
                                                    taskid,
                                                    0.0f,
                                                    1,
                                                    state,
                                                    reason,
                                                    reason,
                                                    trackerName, phase,
                                                    new Counters());
    synchronized (lockObject) {
      // update the actual start-time of the attempt
      TaskStatus oldStatus = tip.getTaskStatus(taskid);
      long startTime = oldStatus == null
      ? JobTracker.getClock().getTime()
          : oldStatus.getStartTime();
      if (startTime < 0) {
        startTime = JobTracker.getClock().getTime();
      }
      status.setStartTime(startTime);
      status.setFinishTime(JobTracker.getClock().getTime());
      boolean wasComplete = tip.isComplete();
      updateTaskStatus(tip, status, ttStatus);
      boolean isComplete = tip.isComplete();
      if (wasComplete && !isComplete) { // mark a successful tip as failed
        String taskType = getTaskType(tip);
        JobHistory.Task.logFailed(tip.getTIPId(), taskType,
            tip.getExecFinishTime(), reason, taskid);
      }
    }
  }
476067
def do_summary(self, args):
        ''''''
        assert args.json or args.text or (args.text is None)
        do_text = args.text

        xd = {}
        for ws in self.task_master.iter_work_specs():
            name = ws['name']
            status = self.task_master.status(name)
            xd[name] = status
        xd['_NOW'] = time.time()

        if args.json:
            self.stdout.write(json.dumps(xd) + '\n')
        else:
            if do_text is None:
                do_text = True

        if do_text:
            self.stdout.write('Work spec               Avail  Pending  Blocked'
                              '   Failed Finished    Total\n')
            self.stdout.write('==================== ======== ======== ========'
                              ' ======== ======== ========\n')
            for name in sorted(xd.keys()):
                if name == '_NOW':
                    continue
                status = xd[name]
                self.stdout.write('{0:20s} {1[num_available]:8d} '
                                  '{1[num_pending]:8d} {1[num_blocked]:8d} '
                                  '{1[num_failed]:8d} {1[num_finished]:8d} '
                                  '{1[num_tasks]:8d}\n'.format(name, status))
387561
private void failTask(final ExecutionAttemptID executionAttemptID, final Throwable cause) {
		final Task task = taskSlotTable.getTask(executionAttemptID);

		if (task != null) {
			try {
				task.failExternally(cause);
			} catch (Throwable t) {
				log.error("Could not fail task {}.", executionAttemptID, t);
			}
		} else {
			log.debug("Cannot find task to fail for execution {}.", executionAttemptID);
		}
	}
940340
private function writeJsonFailureStream(
        CoverFishResult $coverFishResult,
        CoverFishPHPUnitTest $unitTest,
        CoverFishMessageError $mappingError,
        $coverLine
    ) {
        $this->jsonResult['errorCount'] = $coverFishResult->getFailureCount();
        $this->jsonResult['errorMessage'] = $mappingError->getMessageTitle();
        $this->jsonResult['errorCode'] = $mappingError->getMessageCode();
        $this->jsonResult['cover'] = $coverLine;
        $this->jsonResult['method'] = $unitTest->getSignature();
        $this->jsonResult['line'] = $unitTest->getLine();
        $this->jsonResult['file'] = $unitTest->getFile();
    }
127570
def task_failed(sender=None, **kwargs):
    
    if isinstance(sender, UserTaskMixin):
        exception = kwargs['exception']
        if not isinstance(exception, TaskCanceledException):
            # Don't include traceback, since this is intended for end users
            sender.status.fail(str(exception))
        user_task_stopped.send_robust(sender=UserTaskStatus, status=sender.status)