下面列出了 io.netty.handler.codec.http.HttpResponseStatus # INTERNAL_SERVER_ERROR 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public FullHttpResponse respond(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception {
String json = request.content().toString(CharsetUtil.UTF_8);
ClientMessage clientMessage = JSON.fromJson(json, ClientMessage.class);
ClientMessage.Builder responseBuilder = ClientMessage.builder().withCorrelationId(clientMessage.getCorrelationId()).withSource(Address.platformService(PlatformConstants.SERVICE_PEOPLE).getRepresentation());
Pair<MessageBody, HttpResponseStatus> responseTuple;
try {
responseTuple = handleChangePassword(clientMessage, ctx);
} catch (Exception e) {
responseTuple = new ImmutablePair<MessageBody, HttpResponseStatus>(Errors.fromException(e), HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
ClientMessage responseMessage = responseBuilder.withPayload(responseTuple.getLeft()).create();
FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseTuple.getRight(), Unpooled.copiedBuffer(JSON.toJson(responseMessage), CharsetUtil.UTF_8));
httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, BridgeHeaders.CONTENT_TYPE_JSON_UTF8);
return httpResponse;
}
private static final FullHttpResponse http_500(String errorMessage) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR
, Unpooled.wrappedBuffer(errorMessage.getBytes()));
HttpHeaders httpHeaders = response.headers();
httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
return response;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
logger.error("Exception caught in the http connector", e);
if (ctx.attr(MESSAGE_CONTEXT).get() instanceof MessageContext) {
listener.onError(ctx.attr(MESSAGE_CONTEXT).get());
} else {
listener.onError(e.getCause());
}
super.exceptionCaught(ctx, e);
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
ClientMessage request;
MessageBody response;
try {
request = decode(req);
} catch (Throwable t) {
LOGGER.debug("Unable to decode request", t);
return response(HttpResponseStatus.BAD_REQUEST, "plain/text", "Unable to decode request");
}
HttpResponseStatus status = HttpResponseStatus.OK;
try {
/* preHandleValidation is typically a NOOP. However
* there may be times where a RESTHandler might need
* AUTH style checks that require access to the
* ChannelHandlerContext.
*/
assertValidRequest(req, ctx);
response = doHandle(request, ctx);
} catch (Throwable th) {
LOGGER.error("Error handling client message", th);
response = Errors.fromException(th);
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
ClientMessage message = ClientMessage.builder().withCorrelationId(request.getCorrelationId())
.withDestination(request.getSource()).withSource(Addresses.toServiceAddress(PlaceService.NAMESPACE))
.withPayload(response).create();
return response(status, BridgeHeaders.CONTENT_TYPE_JSON_UTF8, JSON.toJson(message));
}
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
ClientMessage request;
MessageBody response;
try {
request = decode(req);
} catch (Throwable t) {
LOGGER.debug("Unable to decode request", t);
return response(HttpResponseStatus.BAD_REQUEST, "plain/text", "Unable to decode request");
}
HttpResponseStatus status = HttpResponseStatus.OK;
try {
/* preHandleValidation is typically a NOOP. However
* there may be times where a RESTHandler might need
* AUTH style checks that require access to the
* ChannelHandlerContext.
*/
assertValidRequest(req, ctx);
response = doHandle(request, ctx);
} catch (Throwable th) {
LOGGER.error("Error handling client message", th);
response = Errors.fromException(th);
status = overrideErrorResponseStatus(th);
if(status == null) {
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
}
ClientMessage message = ClientMessage.builder().withCorrelationId(request.getCorrelationId())
.withDestination(request.getSource()).withSource(Addresses.toServiceAddress(PlaceService.NAMESPACE))
.withPayload(response).create();
return response(status, BridgeHeaders.CONTENT_TYPE_JSON_UTF8, JSON.toJson(message));
}
private void sendError(ChannelHandlerContext ctx) {
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(CfgManager.getInstance().getHttpVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
HttpServerHandler.sendHttpMessage(response, ctx.channel()).
addListener(ChannelFutureListener.CLOSE).
addListener(new FilnalEventListener(ctx, true));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error(cause.getMessage(), cause);
GatewayRunner runner = GatewayRunner.getInstance();
Exception exception = new GatewayException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "UNHANDLED_EXCEPTION_" + cause.getClass().getName());
ContextUtil.setException(ctx.channel(), exception);
runner.errorAction(ctx.channel());
}
private void sendError(ChannelHandlerContext ctx) {
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
HttpServerHandler.sendHttpMessage(response, ctx.channel()).
addListener(ChannelFutureListener.CLOSE).
addListener(new FilnalEventListener(ctx, true));
}
private void handleUnregisterModel(ChannelHandlerContext ctx, String modelName)
throws ModelNotFoundException, InternalServerException, RequestTimeoutException {
ModelManager modelManager = ModelManager.getInstance();
HttpResponseStatus httpResponseStatus = modelManager.unregisterModel(modelName);
if (httpResponseStatus == HttpResponseStatus.NOT_FOUND) {
throw new ModelNotFoundException("Model not found: " + modelName);
} else if (httpResponseStatus == HttpResponseStatus.INTERNAL_SERVER_ERROR) {
throw new InternalServerException("Interrupted while cleaning resources: " + modelName);
} else if (httpResponseStatus == HttpResponseStatus.REQUEST_TIMEOUT) {
throw new RequestTimeoutException("Timed out while cleaning resources: " + modelName);
}
String msg = "Model \"" + modelName + "\" unregistered";
NettyUtils.sendJsonResponse(ctx, new StatusResponse(msg));
}
private HttpResponseStatus readFileUploadData() throws IOException {
while (this.decoder.hasNext()) {
final InterfaceHttpData data = this.decoder.next();
if (data != null) {
try {
logger.info("BODY FileUpload: " + data.getHttpDataType().name() + ": " + data);
if (data.getHttpDataType() == HttpDataType.FileUpload) {
final FileUpload fileUpload = (FileUpload) data;
if (fileUpload.isCompleted()) {
this.requestProcessed = true;
final String format = ImageStoreUtil.checkTemplateFormat(fileUpload.getFile().getAbsolutePath(), fileUpload.getFilename());
if (StringUtils.isNotBlank(format)) {
final String errorString = "File type mismatch between the sent file and the actual content. Received: " + format;
logger.error(errorString);
this.responseContent.append(errorString);
this.storageResource.updateStateMapWithError(this.uuid, errorString);
return HttpResponseStatus.BAD_REQUEST;
}
final String status = this.storageResource.postUpload(this.uuid, fileUpload.getFile().getName());
if (status != null) {
this.responseContent.append(status);
this.storageResource.updateStateMapWithError(this.uuid, status);
return HttpResponseStatus.INTERNAL_SERVER_ERROR;
} else {
this.responseContent.append("upload successful.");
return HttpResponseStatus.OK;
}
}
}
} finally {
data.release();
}
}
}
this.responseContent.append("received entity is not a file");
return HttpResponseStatus.UNPROCESSABLE_ENTITY;
}
private void setResponseStatus(IServletResponse response, APIResponse entity) {
if (Status.SUCCESS.toString().equals(entity.getStatus())) {
response.setStatus(HttpResponseStatus.OK);
} else if (Status.FATAL.toString().equals(entity.getStatus())) {
HttpResponseStatus status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
if (entity instanceof ErrorResponse) {
status = HttpResponseStatus.valueOf(((ErrorResponse) entity).getError().getCode());
}
response.setStatus(status);
}
}
private void sendError(ChannelHandlerContext ctx) {
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(CfgManager.getInstance().getHttpVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
HttpServerHandler.sendHttpMessage(response, ctx.channel()).
addListener(ChannelFutureListener.CLOSE).
addListener(new FilnalEventListener(ctx, true));
}
private void sendError(ChannelHandlerContext ctx) {
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
HttpServerHandler.sendHttpMessage(response, ctx.channel()).
addListener(ChannelFutureListener.CLOSE).
addListener(new FilnalEventListener(ctx, true));
}
private void sendError(ChannelHandlerContext ctx) {
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
HttpServerHandler.sendHttpMessage(response, ctx.channel()).
addListener(ChannelFutureListener.CLOSE).
addListener(new FilnalEventListener(ctx, true));
}
public static FullHttpResponse createInternalError(Throwable throwable) {
ByteBuf badRequestBody =
Unpooled.wrappedBuffer(throwable.getMessage().getBytes(Charset.forName("UTF-8")));
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, badRequestBody);
}
/**
* Create a {@link SQLActionException} out of a {@link Throwable}.
* If concrete {@link ElasticsearchException} is found, first transform it
* to a {@link CrateException}
*/
public static SQLActionException createSQLActionException(Throwable e, Consumer<Throwable> maskSensitiveInformation) {
// ideally this method would be a static factory method in SQLActionException,
// but that would pull too many dependencies for the client
if (e instanceof SQLActionException) {
return (SQLActionException) e;
}
Throwable unwrappedError = SQLExceptions.unwrap(e);
e = esToCrateException(unwrappedError);
try {
maskSensitiveInformation.accept(e);
} catch (Exception mpe) {
e = mpe;
}
int errorCode = 5000;
HttpResponseStatus httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
if (e instanceof CrateException) {
CrateException crateException = (CrateException) e;
if (e instanceof ValidationException) {
errorCode = 4000 + crateException.errorCode();
httpStatus = HttpResponseStatus.BAD_REQUEST;
} else if (e instanceof UnauthorizedException) {
errorCode = 4010 + crateException.errorCode();
httpStatus = HttpResponseStatus.UNAUTHORIZED;
} else if (e instanceof ReadOnlyException) {
errorCode = 4030 + crateException.errorCode();
httpStatus = HttpResponseStatus.FORBIDDEN;
} else if (e instanceof ResourceUnknownException) {
errorCode = 4040 + crateException.errorCode();
httpStatus = HttpResponseStatus.NOT_FOUND;
} else if (e instanceof ConflictException) {
errorCode = 4090 + crateException.errorCode();
httpStatus = HttpResponseStatus.CONFLICT;
} else if (e instanceof UnhandledServerException) {
errorCode = 5000 + crateException.errorCode();
}
} else if (e instanceof ParsingException) {
errorCode = 4000;
httpStatus = HttpResponseStatus.BAD_REQUEST;
} else if (e instanceof MapperParsingException) {
errorCode = 4000;
httpStatus = HttpResponseStatus.BAD_REQUEST;
}
String message = e.getMessage();
if (message == null) {
if (e instanceof CrateException && e.getCause() != null) {
e = e.getCause(); // use cause because it contains a more meaningful error in most cases
}
StackTraceElement[] stackTraceElements = e.getStackTrace();
if (stackTraceElements.length > 0) {
message = String.format(Locale.ENGLISH, "%s in %s", e.getClass().getSimpleName(), stackTraceElements[0]);
} else {
message = "Error in " + e.getClass().getSimpleName();
}
} else {
message = e.getClass().getSimpleName() + ": " + message;
}
StackTraceElement[] usefulStacktrace =
e instanceof MissingPrivilegeException ? e.getStackTrace() : unwrappedError.getStackTrace();
return new SQLActionException(message, errorCode, httpStatus, usefulStacktrace);
}
@SuppressWarnings("unchecked")
@Override
public FullHttpResponse respond(FullHttpRequest request, ChannelHandlerContext ctx) {
String json = request.content().toString(CharsetUtil.UTF_8);
ClientMessage clientMessage = JSON.fromJson(json, ClientMessage.class);
Map<String,Object> attributes = clientMessage.getPayload().getAttributes();
Collection<String> bundleNames = (Collection<String>) attributes.get("bundleNames");
String localeString = (String) attributes.get("locale");
if(StringUtils.isBlank(localeString)) {
localeString = "en-US";
}
if(bundleNames == null || bundleNames.isEmpty()) {
bundleNames = new HashSet<>();
for(I18NBundle bundle : I18NBundle.values()) { bundleNames.add(bundle.getBundleName()); }
}
MessageBody response = null;
HttpResponseStatus responseCode = HttpResponseStatus.OK;
try {
Locale locale = Locale.forLanguageTag(localeString);
Map<String,String> localizedStrings = loadBundles(locale, bundleNames);
response = MessageBody.buildResponse(clientMessage.getPayload(), ImmutableMap.of("localizedStrings", localizedStrings));
} catch(Exception e) {
response = Errors.fromException(e);
responseCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
ClientMessage message = ClientMessage.builder()
.withDestination(clientMessage.getDestination())
.withCorrelationId(clientMessage.getCorrelationId())
.withSource(Address.platformService("i18n").getRepresentation())
.withPayload(response).create();
return new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
responseCode,
Unpooled.copiedBuffer(JSON.toJson(message), CharsetUtil.UTF_8));
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
if (wsUri.equalsIgnoreCase(request.getUri())) {
ctx.fireChannelRead(request.retain());
} else {
if (HttpHeaders.is100ContinueExpected(request)) {
send100Continue(ctx);
}
HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
String path = new URI(request.getUri()).getPath();
if ("/".equals(path)) {
path = "/index.html";
}
URL res = HttpTtyConnection.class.getResource(httpResourcePath + path);
try {
if (res != null) {
DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
InputStream in = res.openStream();
byte[] tmp = new byte[256];
for (int l = 0; l != -1; l = in.read(tmp)) {
fullResp.content().writeBytes(tmp, 0, l);
}
int li = path.lastIndexOf('.');
if (li != -1 && li != path.length() - 1) {
String ext = path.substring(li + 1, path.length());
String contentType;
if ("html".equals(ext)) {
contentType = "text/html";
} else if ("js".equals(ext)) {
contentType = "application/javascript";
} else if ("css".equals(ext)) {
contentType = "text/css";
} else {
contentType = null;
}
if (contentType != null) {
fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
}
}
response = fullResp;
} else {
response.setStatus(HttpResponseStatus.NOT_FOUND);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ctx.write(response);
ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
if (wsUri.equalsIgnoreCase(request.getUri())) {
ctx.fireChannelRead(request.retain());
} else {
if (HttpHeaders.is100ContinueExpected(request)) {
send100Continue(ctx);
}
HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR);
String path = request.getUri();
if ("/".equals(path)) {
path = "/index.html";
}
URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path);
try {
if (res != null) {
DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
InputStream in = res.openStream();
byte[] tmp = new byte[256];
for (int l = 0; l != -1; l = in.read(tmp)) {
fullResp.content().writeBytes(tmp, 0, l);
}
int li = path.lastIndexOf('.');
if (li != -1 && li != path.length() - 1) {
String ext = path.substring(li + 1, path.length());
String contentType;
switch (ext) {
case "html":
contentType = "text/html";
break;
case "js":
contentType = "application/javascript";
break;
default:
contentType = null;
break;
}
if (contentType != null) {
fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
}
}
response = fullResp;
} else {
response.setStatus(HttpResponseStatus.NOT_FOUND);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ctx.write(response);
ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
/**
* Allow its subclass to have a chance to handle the error scenario to return a different response status code from
* the default HttpResponseStatus.INTERNAL_SERVER_ERROR
* @param error
* @return
*/
protected HttpResponseStatus overrideErrorResponseStatus(Throwable error) {
return HttpResponseStatus.INTERNAL_SERVER_ERROR;
}