构造返回对象的DTO

@param result
返回对象结果
@param status
返回状态码
@param error
错误或者异常信息
@param traceId
追踪id
@return ResponseDTO
189709
private ResponseDTO buildResponse(Object result, int status, Exception error, long traceId) {
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setTraceId(traceId);
        responseDTO.setStatus(status);
        if (result != null) {
            responseDTO.setResult(result);
        }
        if (error != null) {
            responseDTO.setError(error);
        }
        return responseDTO;
    }
509998
public static HttpResponseException success(final String destination) {
        return new HttpResponseException() {
            public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
                if (isApply(req)) {
                    // if the submission is via 'apply', show a response in the notification bar
                    applyResponse("notificationBar.show('"+Messages.HttpResponses_Saved()+"',notificationBar.OK)")
                            .generateResponse(req,rsp,node);
                } else {
                    rsp.sendRedirect(destination);
                }
            }
        };
    }
1260260
public static <T> CollectionUpdateResult<T> noop(T result) {
    return new CollectionUpdateResult<>(Status.NOOP, result);
  }
321625
function(err, result) {
        var data=[];
    
        // default route name if not present in XML
        var now=new Date();
        data.name= 'ParseGPX' + now.toISOString(); 
    
        // search for gpx tag
        if (result['gpx'] === undefined) {
            console.log ("Fatal: Not a GPX route/track file [no <gpx></gpx> tag]");
            return (-1);
        }
        // search for track tag
        if (result['gpx']["trk"] !== undefined) {
            // console.log ("track=%s", JSON.stringify(result['gpx']["trk"]));
            data = {
                mode    : 'track',
                name    : result['gpx']["trk"][0].name,
                segment : result['gpx']["trk"][0]["trkseg"][0]['trkpt']
            };
        }
        // search for route tag
        if (result['gpx']["rte"] !== undefined) {
            //console.log ("route=%s", JSON.stringify(result['gpx']["rte"]));
            data = {
                mode    :'route',
                name    :result['gpx']["rte"][0].name,
                segment :result['gpx']["rte"][0]["rtept"]
            };
        }
        if (data.mode === undefined) {
           console.log ("Fatal Not a valid GPX route/track file <trk>|<rte> tag");
           return (-1);
        }
    
        // provide a default name if nothing found in gpxfile
        if (data.name === undefined) {
            now= new Date();
            route.name = 'GGsimulator://' + opts.gpxfile + "/" + now.toISOString();
        } else {
            route.name = 'GGsimulator://' + data.name;
        }
    
        switch (data.mode) {
            case "track":
            var spd, crs, alt,dat;
            for (var trackpts in data.segment)  {
                // console.log ("trackpts[%s]=%s", trackpts, JSON.stringify(data.segment[trackpts]));
                if (data.segment[trackpts]['name'] === undefined) nam= 'TrackPts-' + trackpts; 
                    else nam=data.segment[trackpts]['name'];
                
                lat=parseFloat (data.segment[trackpts]["$"].lat);
                lon=parseFloat (data.segment[trackpts]["$"].lon);
                spd=data.segment[trackpts]['sog'];
                crs=data.segment[trackpts]['course'];
                alt=data.segment[trackpts]['ele'];
                dat=data.segment[trackpts]['time'];
                //console.log ("name=%s  lat=%s lon=%s sog=%s course=%s alt=%s", nam, lat, lon, spd, crs, alt);
                route.waypts.push ({name: nam, lat: lat, lon: lon, date: dat});
                route.count++;
            }
            break;
        case 'route':
            var nam, lat, lon;
            for (var routepts in data.segment)  {
                // console.log ("routepts[%s]=%s", routepts, JSON.stringify(data.segment[routepts]));
                if (data.segment[routepts]['name'] === undefined)
                    nam= 'TrackPts-' + routepts;
                else
                    nam=data.segment[routepts]['name'];

                lat=parseFloat (data.segment[routepts]["$"].lat);
                lon=parseFloat (data.segment[routepts]["$"].lon);
                // console.log ("name=%s  lat=%s lon=%s", nam, lat, lon);
                route.waypts.push ({name: nam, lat: lat, lon: lon});
                route.count++;
            }
            break;
        }
    }
1221170
@Override
    public InsertStatus insertStatus(String transId, Integer errorPage, Integer errorLimit) {
        return dataOperations.insertStatus(transId, errorPage, errorLimit);
    }
631100
private static Observable<ViewQueryResponse> passThroughOrThrow(final ViewQueryResponse response) {
        final int responseCode = response.responseCode();
        if (responseCode == 200) {
            return Observable.just(response);
        }

        return response
            .error()
            .map(new Func1<String, ViewQueryResponse>() {
                @Override
                public ViewQueryResponse call(String error) {
                    if (shouldRetry(responseCode, error)) {
                        throw SHOULD_RETRY;
                    }
                    return response;
                }
            })
            .singleOrDefault(response);
    }
32364
@Override
    public Response toResponse(ErrorDto e)
    {
        // String type = headers.getContentType() == null ? MediaType.APPLICATION_JSON : headers.getContentType();
        return Response.status(e.httpStatus).entity(e).type(MediaType.APPLICATION_JSON).build();
    }
943613
private void postProcess(ProcessMethodCallback callback, TransactionContext txContext,
                           InputDatum input, ProcessMethod.ProcessResult result) {
    InputContext inputContext = input.getInputContext();
    Throwable failureCause = null;
    FailureReason.Type failureType = FailureReason.Type.IO_ERROR;
    try {
      if (result.isSuccess()) {
        // If it is a retry input, force the dequeued entries into current transaction.
        if (input.getRetry() > 0) {
          input.reclaim();
        }
        txContext.finish();
      } else {
        failureCause = result.getCause();
        failureType = FailureReason.Type.USER;
        txContext.abort();
      }
    } catch (Throwable e) {
      LOG.error("Transaction operation failed: {}", e.getMessage(), e);
      failureType = FailureReason.Type.IO_ERROR;
      if (failureCause == null) {
        failureCause = e;
      }
      try {
        if (result.isSuccess()) {
          txContext.abort();
        }
      } catch (Throwable ex) {
        LOG.error("Fail to abort transaction: {}", inputContext, ex);
      }
    }

    try {
      if (failureCause == null) {
        callback.onSuccess(result.getEvent(), inputContext);
      } else {
        callback.onFailure(result.getEvent(), inputContext,
                           new FailureReason(failureType, failureCause.getMessage(), failureCause),
                           createInputAcknowledger(input));
      }
    } catch (Throwable t) {
      LOG.error("Failed to invoke callback.", t);
    }
  }
103050
@Override
	public void getBindingsResult(int resultCode,
			List<RegistrationBinding> bindings) {
		ServerTransaction serverTransaction = getRegisterTransactionToReply();
		if (serverTransaction == null) {
			tracer.warning("failed to find SIP server tx to send response");
			return;
		}
		try {
			if (resultCode < 300) {
				sendRegisterSuccessResponse(resultCode, bindings,
						serverTransaction);
			} else {
				sendErrorResponse(resultCode, serverTransaction);
			}
		} catch (Exception e) {
			tracer.severe("failed to send SIP response", e);
		}
	}
533560
function(errOrMessage, result) {
        var err = (errOrMessage instanceof Error) ? errOrMessage : new Error(errOrMessage);
        result = result || {};
        result.error = err;
        result.status = 'error';
        err.result = result;
        return err;
    }
49610
public void onSuccess(T result) {
        try {
            statusLock.lock();
            value = result;
            status = new RequestStatus(RequestStatusCode.OK);
            statusLockChangedCondition.signalAll();
        } catch (Exception e) {
            status = new RequestStatus(RequestStatusCode.ERROR);
            exception = new JoynrRuntimeException(e);
        } finally {
            statusLock.unlock();
        }
    }
203525
private void signalObjectError(WebContext ctx, HttpResponseStatus status, String message) {
        if (ctx.getRequest().method() == HEAD) {
            ctx.respondWith().status(status);
        } else {
            ctx.respondWith().error(status, message);
        }
        log.log(ctx.getRequest().method().name(),
                message + " - " + ctx.getRequestedURI(),
                APILog.Result.ERROR,
                CallContext.getCurrent().getWatch());
    }
1327846
function (type, error = null, id = null) {
    type = type.toUpperCase()
    let errors = {
        'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.',
        'BUSY': 'The server providing the info is busy right now. Try again.',
        'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.',
        'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.',
        'DOWN': 'The provider server is currently down. Try Again later.',
        'PARSER': 'Something went wrong when parsing the provider website.',
        'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.'
    }

    let message = error != null ? error : errors[type]
    message = id != null ? message + ' ID:' + id : message
    return new Error(type + ' - ' + message)
}
1324565
@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{batchId}")
    @Description("Return a batch query's status and results if done")
    public Response getBatchById(@Context HttpServletRequest req,
                                 @PathParam("batchId") String batchId) {
        _validateBatchId(batchId);
        PrincipalUser currentOwner = validateAndGetOwner(req, null);

        BatchMetricQuery batch = batchService.findBatchById(batchId);
        if (batch != null) {
            PrincipalUser actualOwner = userService.findUserByUsername(batch.getOwnerName());
            validateResourceAuthorization(req, actualOwner, currentOwner);
            return Response.ok(BatchDto.transformToDto(batch), MediaType.APPLICATION_JSON).build();
        }
        throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND);
    }
494747
function(err, results) {
  if(err) {
    this.success = false;
    this.error = err;
    this.results = null;

    // customize error for error types
    if(util.isError(err)) {
      this.error = {
        message: err.message,
        type: err.type,
        arguments: err.arguments
      };
      if(NODE_ENV === 'development') {
        this.error.stack = err.stack;
      }
    }    

  } else {
    this.success = true;
    this.error = null;      
    this.results = convertToClient(results);    
  }
}
884544
private ValidationMessage<Origin> reportError(ValidationResult result, Origin origin, String messageId,
                                                  Object... params) {
        ValidationMessage<Origin> message =
                EntryValidations.createMessage(origin, Severity.ERROR, messageId, params);
        result.append(message);
        return message;
    }
222235
def _onerror(self, result):
        
        self._set_status("FAILED", result)
        logger.error(
            "{}.Failed: {}[{}]: {}".format(
                self.__class__.__name__, self.__class__.path, self.uuid, result
            ),
            extra=dict(
                kmsg=Message(
                    self.uuid, entrypoint=self.__class__.path,
                    params=self.params
                ).dump(),
                kresult=ResultSchema().dump(result) if result else dict()
            )
        )
        return self.onerror(result)