001package io.ebean.config.dbplatform; 002 003import io.ebean.AcquireLockException; 004import io.ebean.DataIntegrityException; 005import io.ebean.DuplicateKeyException; 006 007import javax.persistence.PersistenceException; 008import java.sql.SQLException; 009import java.util.Collections; 010import java.util.Map; 011 012/** 013 * Translate SQLException based on SQLState codes. 014 */ 015public class SqlCodeTranslator implements SqlExceptionTranslator { 016 017 private final Map<String,DataErrorType> map; 018 019 /** 020 * Create given the map of SQLState codes to error types. 021 */ 022 public SqlCodeTranslator(Map<String,DataErrorType> map) { 023 this.map = map; 024 } 025 026 /** 027 * Create "No-op" implementation. 028 */ 029 public SqlCodeTranslator() { 030 this.map = Collections.emptyMap(); 031 } 032 033 @Override 034 public PersistenceException translate(String message, SQLException e) { 035 036 DataErrorType errorType = map.get(e.getSQLState()); 037 if (errorType == null) { 038 // fall back to error code 039 errorType = map.get(String.valueOf(e.getErrorCode())); 040 } 041 if (errorType != null) { 042 switch (errorType) { 043 case AcquireLock: 044 return new AcquireLockException(message, e); 045 case DuplicateKey: 046 return new DuplicateKeyException(message, e); 047 case DataIntegrity: 048 return new DataIntegrityException(message, e); 049 } 050 } 051 // return a generic exception 052 return new PersistenceException(message, e); 053 } 054}