Includes:

  1. Error Handling
  2. General Validation
  3. Actuator
  4. Aspect

Error Handling

Reference solutions:

  1. Zalando problem-spring-web
  2. A Guide to the Problem Spring Web Library
  3. Spring Error Handing
  4. Spring Error Responses
  5. RFC9457 - Problem Details for HTTP APIs

HopeExceptionHandler is an implementation of @ControllerAdvice.

  1. Finds the most suitable Exception Handler based on the exception class.
  2. Handles exceptions.
  3. Adds exception headers (HTTP).
  4. Prints exceptions.
  5. Returns results.

Built-in Error Handling

Class NameNote
AsyncRequestTimeoutExceptionHandlerHandles AsyncRequestTimeoutException
BindExceptionHandlerHandles BindingResult
ConstraintViolationExceptionHandlerHandles ConstraintViolationException
HopeErrorDetailExceptionHandlerHandles HopeErrorDetailException
HttpMediaTypeExceptionHandlerHandles HttpMediaTypeException
HttpMessageNotReadableExceptionHandlerHandles HttpMessageNotReadableException
HttpMessageNotWritableExceptionHandlerHandles HttpMessageNotWritableException
MissingRequestValueExceptionHandlerHandles MissingRequestValueException
ObjectOptimisticLockingFailureApiExceptionHandlerHandles ObjectOptimisticLockingFailureException
ServerErrorExceptionHandlerHandles ServerErrorException
ServerWebInputExceptionHandlerHandles ServerWebInputException
SpringSecurityExceptionHandlerHandles AccessDeniedException & UsernameNotFoundException & org.springframework.security.authentication.*
TypeMismatchExceptionHandlerHandles TypeMismatchException

Exceptions will be processed by the Exception Handler and encapsulated into ServerErrorEnum objects before being returned to the client.

Error CodeError TitleError DescriptionError Description 2
1003000001MISSING_REQUEST_PARAMETERMissing Request ParameterRequest parameter missing
1003000011MISSING_PATH_VARIABLEMissing Path VariableMissing path parameter
1003000012MISSING_MATRIX_VARIABLEMissing MatrixVariable ExceptionMissing Matrix parameter
1003000013MISSING_REQUEST_COOKIEMissing RequestCookie ExceptionValidation error, cookie missing
1003000014MISSING_REQUEST_HEADERMissing RequestHeader ExceptionValidation error, header missing
1003000023HTTP_REQUEST_METHOD_NOT_SUPPORTEDHttp Request Method Not SupportedUnsupported HTTP request method
1003000024HTTP_MEDIA_TYPE_NOT_SUPPORTEDHttp MediaType Not SupportedUnsupported HTTP media type
1003000025HTTP_MEDIA_TYPE_NOT_ACCEPTABLEHttp MediaType Not AcceptableIncorrect HTTP media type
1003000036SERVLET_REQUEST_BINDINGRequest Binding ExceptionRequest data binding error, data validation issue
1003000037TYPE_MISMATCHType MismatchValidation error
1003000038METHOD_ARGUMENT_NOT_VALIDMethod Argument Not ValidValidation error
1003000039CONSTRAINT_VIOLATIONConstraint ViolationValidation error
1003000040SERVER_ERRORServer Error, exposes extra information about a controller method that failed, or a method argument that could not be resolved.Internal server error
1003000041BINDING_ERRORServer Error, exposes extra information about a controller method that failed, or a method argument that could not be resolved.Data binding error
1003000051HTTP_MESSAGE_NOT_READABLEHttp Message Not ReadableHttp input unreadable
1003000052HTTP_MESSAGE_NOT_WRITABLEHttp Message Not WritableHttp output unwritable
1003000060MISSING_REQUEST_PARTMissing Servlet Request Part Exception, ‘multipart/form-data’ requestUpload request validation failed
1003000061ASYNC_REQUEST_TIMEOUTAsync Request Timeout ExceptionAsync request timeout
1003000101ORM_OBJECT_OPTIMISTIC_LOCKING_FAILUREException thrown on an optimistic locking violation for a mapped object.Optimistic lock error
1003000501SECURITY_ACCESS_DENIEDAccess DeniedAccess denied
1003000502SECURITY_ACCOUNT_EXPIREDAccount ExpiredAccount expired
1003000503SECURITY_AUTHENTICATION_CREDENTIALS_NOT_FOUNDAuthentication Credentials Not FoundAuthentication credentials missing
1003000504SECURITY_AUTHENTICATION_SERVICEAuthentication ServiceAuthorization service error
1003000505SECURITY_BAD_CREDENTIALSBad CredentialsIncorrect authorization
1003000506SECURITY_USER_NOT_FOUNDUser Not FoundUser not found
1003000507SECURITY_INSUFFICIENT_AUTHENTICATIONInsufficient AuthenticationAuthorization validation error
1003000508SECURITY_LOCKEDAccount LockedAccount locked
1003000509SECURITY_DISABLEDAccount DisabledAccount disabled
1003000510SECURITY_AUTHENTICATIONAuthentication FailAuthorization error
1003000511SECURITY_ANONYMOUS_UN_CHANGEABLEAuthentication Try Update Anonymous propertiesUpdate anonymous error
1003000512SECURITY_JWT_EXPIREJWT ExpireJWT expired
1003000513SECURITY_JWT_UNSUPPORTEDJWT UnsupportedJWT unsupported
1003000514SECURITY_JWT_MALFORMEDJWT MalformedJWT format error
1003000515SECURITY_JWT_SIGNATUREJWT SignatureJWT signature error
1003000516SECURITY_JWT_GENERICJWT Generic ExceptionGeneral JWT error

BindingResult

BindingResult is not an exception, but its implementation classes include BindException & WebExchangeBindException, which are parameter binding exception classes.

Field binding errors are translated into BINDING_ERROR type errors.

ConstraintViolationException

Validation exceptions are translated from ConstraintViolation to CONSTRAINT_VIOLATION type errors.

HopeErrorDetailException

HopeErrorDetailException is an internal general exception class that includes:

  1. message
  2. cause
  3. List of hope.common.api.error.Error

Error Configuration

Configuration path: hope.error; Configuration object: HopeProblemProperties

ConfigurationNote
codesException to code mapper Map<String, String>
logLevelLog output detail level
errorCodeStrategyError class name handling method
httpStatusesClass to HTTP status mapping Map<String, HttpStatus>
searchSuperClassHierarchyWhether to search superclass in the hierarchy
addPathToErrorWhether to add the path to the error details
messagesOutput messages mapping Map<String, String>

LogLevel

ConfigurationNote
NO_LOGGINGNo logs printed
MESSAGE_ONLYOnly include message
WITH_STACKTRACEEntire stack trace

ErrorCodeStrategy

NameNote
FULL_QUALIFIED_NAMEhope.common.spring.problem.Example
ALL_CAPShope.common.spring.problem.Example -> EXAMPLE

General Validation

NameNote
@ChinaMobileChina mobile number validation
@EnumsEnum list validation

Actuator

HopeProjectInfoContributor includes runtime context information for debugging:

NameNote
domainDomain information
applicationApplication name
mainClassEntry class
mainPackageMain package
stubBuildTimeStub compilation time
projectMain project Project information
protoProto Project information

Project includes:

  1. Artifact
  2. Name
  3. Description
  4. Module

And other information.

Aspect

AspectManager primarily manages external service aspects: organizes runtime context Aspect weaving, running as follows:

public ResponseEntity<Result<String>> exampleSayHello() {
    final SimpleResultBuilder<String> builder = new SimpleResultBuilder<String>();

    try {
    	aspect().before("/demo-001/hello-world" );
    	_service.exampleSayHello(builder);
    	ResponseEntity<Result<String>> res = builder.done();
    	aspect().after("/demo-001/hello-world", res  );
    	return res;
    } catch (Throwable exception ) { 
    	logger.error("FAIL_ACTION METHOD:[exampleSayHello] PATH:[/demo-001/hello-world]",exception);
    	aspect().exception("/demo-001/hello-world", exception  );
    	throw exception;
    }
  }

  public AspectManager aspect() {
    return AspectManager.get();
  }

Pagination

PageRequestGuardian is responsible for validating pagination parameters to prevent excessively large page sizes.

Refer

  1. Zalando problem-spring-web
  2. A Guide to the Problem Spring Web Library
  3. Spring Error Handing
  4. Spring Error Responses
  5. RFC9457 - Problem Details for HTTP APIs