SpringBoot-- abnormal unified treatment

  First on the code, and manual capture without capture exception handling exception:

@GetMapping("/error1")
    public String error1() {
        int i = 10 / 0;
        return "test1";
    }

    @ResponseBody
    @GetMapping("/error2")
    public Map<String, String> error2() {
        Map<String, String> result = new HashMap<>(16);
        try{
            int i = 10 / 0;
            result.put("code", "200");
            result.put ( "Data", "specific result set returned" );
        } catch (Exception e) {
            result.put("code", "500");
            result.put ( "Message", "request error" );
        }
        return result;
    }

  One of the issues not say any more, due to various problems, so the need for a unified capture abnormal

  1, import-dependent

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

  2, custom exception class

package com.example.demo.entity;

import lombok.Data;

@Data
public class ErrorResponse {
private int code;
private String message;

public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
}

public ErrorResponse() {

}

public ErrorResponse OK(String message){
this.code = 200;
this.message = message;
return this;
}

public void OK(){
this.code = 200;
this.message = "";
}
}

  3, the definition of abnormal template

package com.example.demo.entity;

import lombok.Data;

@Data
public class ErrorResponse {
    private int code;
    private String message;

    public ErrorResponse(int code, String message) {
        this.code = code;
        this.message = message;
    }
}

  4, abnormal interceptor

  When the focus of this step requires special note,

  @ControllerAdvice capture Controller layer thrown exception, if you add @ResponseBody information was returned in JSON format.

  @RestControllerAdvice corresponds with @ControllerAdvice @ResponseBody combination.

   @ExceptionHandler unitary one kind of exception classes, the repetition rate of the code decrease, reduce complexity. GlobalExceptionHandler create a class and add annotations on @RestControllerAdvice can define exception notification class, and then add on @ExceptionHandler the method defined to achieve unusual catch ...

package com.example.demo.utils;

import com.example.demo.entity.ErrorResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(LclException.class)
    public ErrorResponse lclExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response){
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        LclException exception = (LclException) e;
        return new ErrorResponse(exception.getCode(),exception.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public ErrorResponse runtimeExcetionHandler(HttpServletRequest request, final Exception e,HttpServletResponse response){
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        RuntimeException exception = (RuntimeException) e;
        return new ErrorResponse(400,exception.getMessage());
    }


    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if(ex instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            return new ResponseEntity<>(new ErrorResponse(status.value(),exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
        }

        if(ex instanceof MethodArgumentTypeMismatchException){
            MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
            return new ResponseEntity<>(new ErrorResponse(status.value(),"参数转换异常"),status);
        }

        return  new new ResponseEntity <> ( new new ErrorResponse (status.value (), "argument translation exception" ), Status);
    }


}

  5, the test class

@ResponseBody
@GetMapping("/error3")
public ErrorResponse error3(Integer num) throws LclException{
if(num == null){
throw new LclException(12345,"num不允许为空");
}
int i = 10/num;
return (new ErrorResponse()).OK(i+"");
}

  6, the test

 

 

  

 

Guess you like

Origin www.cnblogs.com/liconglong/p/11716268.html