Spring Boot教程
作者: 时海
ExceptionHandler实现统一异常处理

SpringBoot使用ControllerAdvice和ExceptionHandler实现统一处理异常

package com.example.boot;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ErrorHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, Object> handle(HttpServletRequest req, Exception ex) {
        Map<String, Object> result = new HashMap<>();
        result.put("errorCode", "404");
        result.put("errorMsg", ex.getMessage());
        return result;
    }
}




一个创业中的苦逼程序员
  • 回复
隐藏