ResponseStatusException reason is optional (with lazily constructed message)

Issue: SPR-15524
This commit is contained in:
Juergen Hoeller
2017-05-06 12:53:03 +02:00
parent edbf9fa74e
commit 25aef4d3cc
6 changed files with 69 additions and 52 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package org.springframework.web.server;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.core.NestedRuntimeException;
import org.springframework.http.HttpStatus;
import org.springframework.util.Assert;
@@ -24,6 +25,7 @@ import org.springframework.util.Assert;
* Base class for exceptions associated with specific HTTP response status codes.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 5.0
*/
@SuppressWarnings("serial")
@@ -35,37 +37,56 @@ public class ResponseStatusException extends NestedRuntimeException {
/**
* Constructor with a response code and a reason to add to the exception
* Constructor with a response status.
* @param status the HTTP status (required)
*/
public ResponseStatusException(HttpStatus status) {
this(status, null, null);
}
/**
* Constructor with a response status and a reason to add to the exception
* message as explanation.
* @param status the HTTP status (required)
* @param reason the associated reason (optional)
*/
public ResponseStatusException(HttpStatus status, String reason) {
this(status, reason, null);
}
/**
* Constructor with a nested exception.
* Constructor with a response status and a reason to add to the exception
* message as explanation, as well as a nested exception.
* @param status the HTTP status (required)
* @param reason the associated reason (optional)
* @param cause a nested exception (optional)
*/
public ResponseStatusException(HttpStatus status, String reason, Throwable cause) {
super("Request failure [status: " + status + ", reason: \"" + reason + "\"]", cause);
Assert.notNull(status, "'status' is required");
Assert.notNull(reason, "'reason' is required");
super(null, cause);
Assert.notNull(status, "HttpStatus is required");
this.status = status;
this.reason = reason;
}
/**
* The HTTP status that fits the exception.
* The HTTP status that fits the exception (never {@code null}).
*/
public HttpStatus getStatus() {
return this.status;
}
/**
* The reason explaining the exception.
* The reason explaining the exception (potentially {@code null} or empty).
*/
public String getReason() {
return this.reason;
}
@Override
public String getMessage() {
String msg = "Response status " + this.status + (this.reason != null ? " with reason \"" + reason + "\"" : "");
return NestedExceptionUtils.buildMessage(msg, getCause());
}
}