View Javadoc
1   /*
2   * Copyright 2019-2026 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.ldaptive;
18  
19  import java.util.Optional;
20  import org.ldaptive.LdapException;
21  import org.ldaptive.ResultCode;
22  
23  /**
24   * The default ldaptive error handler.
25   *
26   * @author Christian Bremer
27   */
28  public class DefaultLdaptiveErrorHandler extends AbstractLdaptiveErrorHandler {
29  
30    /**
31     * Instantiates a new default ldaptive error handler.
32     */
33    public DefaultLdaptiveErrorHandler() {
34      super();
35    }
36  
37    @Override
38    public LdaptiveException map(LdapException ldapException) {
39      return LdaptiveException.builder()
40          .reason(Optional.ofNullable(ldapException)
41              .map(LdapException::getMessage)
42              .orElse("Unknown"))
43          .errorCode(errorCode(ldapException))
44          .httpStatus(httpStatus(ldapException))
45          .cause(ldapException)
46          .build();
47    }
48  
49    private int httpStatus(LdapException ldapException) {
50      return Optional.ofNullable(ldapException)
51          .map(LdapException::getResultCode)
52          .map(this::httpStatus)
53          .orElse(500);
54    }
55  
56    private int httpStatus(ResultCode resultCode) {
57      ResultCode code = Optional.ofNullable(resultCode).orElse(ResultCode.OTHER);
58      return switch (code) {
59        case SUCCESS -> 200;
60        case INVALID_CREDENTIALS -> 400;
61        case NO_SUCH_OBJECT -> 404;
62        default -> 500;
63      };
64    }
65  
66    private String errorCode(LdapException ldapException) {
67      return Optional.ofNullable(ldapException)
68          .map(LdapException::getResultCode)
69          .map(ResultCode::name)
70          .orElse(null);
71    }
72  
73  }