Groovy web console

subscribe to the feed Subscribe
to this
site
ErrorManagement wihtout statics (via #groovywebconsole)
tweet this snippet Tweet
this
script

ErrorManagement wihtout statics

Published 11 months ago by Luis Epifanio with tags ErrorManagement wihtout statics
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
import groovy.transform.InheritConstructors

@InheritConstructors
@ToString
class GenericException extends Exception{
  int status
  String errorKey
  String userTitle
  String userMessage
}

@ToString
enum DestinationErrorResolver {
  NOT_FOUND_ZIP_CODE('not_found_zip_code'){
      @Override
      GenericException resolveMessage(){
        GenericException error = buildBaseGenericException(keyCode)
        error.setUserMessage('NO_ZIP_CODE')
        error
      }
    },
    GET_ZIPCODE_ERROR('get_zipcode_error'){
        @Override
        GenericException resolveMessage(){
          GenericException error = buildBaseGenericException(keyCode)
          error.setUserMessage('ERROR_ZIP_CODE')
          error
        }
      },
      DEFAULT(''){
        @Override
        GenericException resolveMessage(){
          GenericException error = buildBaseGenericException(keyCode)
          error.setUserMessage('DEFAULT_ERROR')
          error
        }
        public boolean matches(String aCode){
          true
        }
      }

      final String keyCode

      DestinationErrorResolver(String _keyCode){
        assert null != _keyCode
        this.keyCode = _keyCode
      }

      boolean matches(String aCode){
        keyCode.equalsIgnoreCase(aCode)
      }

      public GenericException resolveMessage(){
        GenericException error = buildBaseGenericException(keyCode)
        error.setUserMessage('DEFAULT')
        error
      }

      GenericException buildBaseGenericException(String errorCode) {
        // Creamos una GenericException base para completar con datos despu?
        GenericException errorResponse = new GenericException('There was a problem while fetching packing options')
        errorResponse.setStatus(400)
        errorResponse.setErrorKey(errorCode)
        errorResponse.setUserTitle('')
        return errorResponse
      }

      public static GenericException resolveError(String errorCode) {
        DestinationErrorResolver resolver = values().find{ it.matches(errorCode) } ?: DestinationErrorResolver.DEFAULT
        return resolver.resolveMessage()
      }
    }

    println DestinationErrorResolver.resolveError('not_found_zip_code')
    println DestinationErrorResolver.resolveError('cualca')